题目
给你一个由
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
你可以按 任意顺序 返回答案 。
注意
- 测试用例 num = [1000000000,1000000000,1000000000,1000000000], target = -294967296
代码出现溢出错误,是因为int的只能到表示[-2147483648,2147483647],所以在判断num[a]+num[b]+num[c]+num[d]<target时会溢出。
代码
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
Arrays.sort(nums);
int l = nums.length;
for (int i = 0; i < l - 2; i++) {
for (int j = i + 1; j < l - 1; j++) {
int left = j + 1;
int right = l - 1;
while (left < right) {
long ll = (long) nums[i] + nums[j] + nums[left] + nums[right];
if (ll == target) {
List<Integer> lists = new ArrayList<Integer>();
lists.add(nums[i]);
lists.add(nums[j]);
lists.add(nums[left]);
lists.add(nums[right]);
list.add(lists);
left++;
right--;
} else if (ll < target) {
left++;
} else if (ll > target) {
right--;
}
}
}
}
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
return list;
}
}