力扣:18.四数之和
题目:
给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
解析:
与上一题类似,无非是三个数变为四个数,只需要将这两个数分别视为上一题的第一位即可,罗列出这两位的所有情况,然后用双指针选择 second,和 third。
代码:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> v;
sort(nums.begin(),nums.end());
for(int i = 0; i < nums.size() ; i++){
if(i > 0 && nums[i] == nums[i-1]) continue ;
for(int first = i + 1; first < nums.size(); first++){
if(first > i+1 && nums[first] == nums[first-1]) continue;
int second = first+1;
int third = nums.size()-1;
while(second < third){
if(nums[first]+nums[i] > target-nums[third]-nums[second]){ third--;}
else if(nums[first]+nums[i] < target-nums[third]-nums[second]) {second++;}
else {
v.push_back(vector<int>{nums[i],nums[first],nums[second],nums[third]});
while(second < third && nums[second] == nums[second+1]) second++;
while(second < third && nums[third] == nums[third-1]) third--;
second++;
third--;
}
}
}
}
return v;
}
};
用这两块代码过不去,数组中元素类型为int,当元素为10的九次,这四个元素相加超出 int 范围,报错。
if(nums[second]+nums[third]+nums[first]+nums[i] > target)
else if(nums[second]+nums[third]+nums[first]+nums[i] < target)
正确代码:
if(nums[first]+nums[i] > target-nums[third]-nums[second])
else if(nums[first]+nums[i] < target-nums[third]-nums[second])
数字较大时要注意,通过移位的方式来使数值变小。