脚本宝典收集整理的这篇文章主要介绍了LeetCode第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 你可以按 任意顺序 返回答案 。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/4sum
示例
输入:nums = [1,0,-1,0,-2,2], target = 0 输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
输入:nums = [2,2,2,2,2], target = 8 输出:[[2,2,2,2]]
使用双指针法 先将数组排序,for循环取到两个数之后,再建立左指针,右指针。左指针靠近第二层for循环,右指针放在数组的尾端。(其实可以理解为四指针法,两个for循环也可以算作两个指针)。若sum小于target左指针右移,若sum大于target右指针左移,如此实现指针的动态性。 注:一旦找到符合要求的结果,则两个指针要同时内缩,否则陷入死循环!
public List<List<Integer>> solution(int[] nums,int target){
//建立结果容器(因为要反复添加考虑到重复问题,故使用HashSet结构)
Set<List<Integer>> box = new HashSet<>();
//将数组排序
Arrays.sort(nums);
//建立左右指针
int left;
int right;
for(int i = 0;i < nums.length;i++){
for(int p = i + 1;p < nums.length;p++){
left = p + 1;
right = nums.length - 1;
while(left < right){
if(nums[i]+nums[p]+nums[left]+nums[right] < target){
left++;
}else if(nums[i]+nums[p]+nums[left]+nums[right] > target){
right--;
}else {
box.add(Arrays.asList(new Integer[]{nums[i],nums[p],nums[left],nums[right]}));
right--;
left++;
}
}
}
}
return new ArrayList<>(box);
}
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 - 1] == nums[i]) {
continue;
}
for (int j = i + 1; j < nums.length; j++) {
if (j > i + 1 && nums[j - 1] == nums[j]) {
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (right > left) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
left++;
right--;
}
}
}
}
return result;
}
方法一比较粗糙,效率较低,而方法二加入了一些剪枝操作,更加高效快捷!
以上是脚本宝典为你收集整理的LeetCode第18题:四数之和全部内容,希望文章能够帮你解决LeetCode第18题:四数之和所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。