- 四数相加 II
本题总共有4个数组,相加等于0,那么意味着任意两个数组的和 + 剩余两个数组的和 等于0
所以先记录任意两个数组的和,并且记录每个和出现的次数
然后和剩下的两个数组的和进行匹配,如果匹配上了从map里拿到次数,累加
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> map = new HashMap<>();
int temp = 0;
int res = 0;
//统计两个数组中的元素之和,同时统计出现的次数,放入Map
for(int i : nums1){
for(int j : nums2){
temp = i + j;
if(map.containsKey(temp)){
map.put(temp, map.get(temp) + 1);
}else{
map.put(temp, 1);
}
}
}
//统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数
for(int i : nums3){
for(int j : nums4){
temp = i + j;
if(map.containsKey(-temp)){
res += map.get(-temp);
}
}
}
return res;
}
}
- 三数之和
本题用双指针,双指针一定要是有序的,所以先排序
先固定最左边的,然后最规定Left和right,依次循环
记得去重,先运算一次,如果当前值和前面的一个值重复,移动指针
如果最小的值都大于0了,则移动指针,后面不必计算了
class Solution {
public List<List<Integer>> threeSum(int[] nums){
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
if(nums[i] > 0){
return result;
}
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{
result.add(Arrays.asList(nums[i],nums[left],nums[right]));
while(left < right && nums[right] == nums[right - 1]) right--;
while(left < right && nums[left] == nums[left + 1]) left++;
right--;
left++;
}
}
}
return result;
}
}
- 四数之和
三数之和的升级版,外层两个for循环,内层用双指针
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
if(i > 0 && nums[i] == nums[i - 1]){
continue;
}
for(int j = i + 1; j < nums.length; j++){
if(j > i + 1 && nums[j] == nums[j - 1]){
continue;
}
if(nums[j] > 0 && nums[i] + nums[j] > target){
break;
}
int left = j + 1;
int right = nums.length - 1;
while(left < right){
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if(sum < target){
left++;
}else if(sum > target){
right--;
}else{
result.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
while(left < right && nums[right] == nums[right - 1]) right--;
while(left < right && nums[left] == nums[left + 1]) left++;
right--;
left++;
}
}
}
}
return result;
}
}