leetcode18. 四数之和

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

思路,两层循环选出两个数字,对剩下的数字跑双指针。

三数之和

class Solution {
    public List<List<Integer>> fourSum(int[] nums,int target) {
    	List<List<Integer>> listArr=new ArrayList<>();
        int len=nums.length;
        int left,right;
        Arrays.sort(nums);

        for(int i=0;i<len;++i){
        	if(i>0 && nums[i] == nums[i-1]) continue;
            for(int j=i+1;j<len;++j){
                if(j>i+1 && nums[j] == nums[j-1]) continue;
                left=j+1;
                right=len-1;
                while(left<right) {
                    int four=nums[left]+nums[right]+nums[i]+nums[j];
                    if(four>target){
                        right--;
                    }else if(four<target){
                        left++;
                    }else{
                	    listArr.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
                	    while(left<right && nums[left]==nums[left+1])left++;
                	    while(left<right && nums[right]==nums[right-1])right--;
                	    left++;
                	    right--;
                    }
                }
            }

        }
        return listArr;
    }
}
发布了555 篇原创文章 · 获赞 1万+ · 访问量 133万+

猜你喜欢

转载自blog.csdn.net/hebtu666/article/details/104329663