力扣454.四数相加2
链接: link
思路
这道题用的方式很巧,我们首先用2个for循环遍历2个数组,将所有可能的和的到,然后存入map集合中,key为a+b,value为a+b出现的次数。
接着再用2个for循环遍历剩余2个数组,用0去减两个数的和,再去map中找满足条件的结果,最后将所有结果相加即可。
方法1:
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map <Integer,Integer> map = new HashMap<Integer,Integer>();
int res = 0;
for(int i : nums1){
for(int j : nums2){
int sum = i + j;
map.put(sum,map.getOrDefault(sum,0) + 1); //key为两数之和,value为这个和出现的次数
}
}
for(int i : nums3){
for(int j : nums4){
int sum1 = i + j;
res += map.getOrDefault(-sum1,0); // 通过0-剩余两个数组的两数之和,反解map中有多少个满足条件的
}
}
return res;
}
}
15.三数之和
思路
这道题要求是三元组不能相同,但是三元组里的元素可以相同。
还有个难点就是关于去重的问题,a、b、c三个数分别如何去重等。
这道题我自己想不到好的思路,直接放卡神的思路吧,感兴趣可以去看看,在分析是和前一个数比较还是和后一个数比较的时候很值得思考。
链接: link
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for(int i =0;i<nums.length;i++){
if(nums[i] > 0){
return res;
}
// 去重a
if(i>0 && nums[i] == nums[i-1]){
continue;
}
int left = i+1;
int right = nums.length - 1;
while(left < right){
int sum = nums[i] + nums[left] + nums[right];
if(sum > 0){
right--;
}else if(sum < 0){
left++;
}else{
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
right--;
left++;
}
}
}
return res;
}
}