其他分享
首页 > 其他分享> > leetcode.code.18. 四数之和

leetcode.code.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
你可以按 任意顺序 返回答案 。

 

示例 1:

输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:

输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]
 

提示:

1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109

 

 

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;     } }

标签:四数,target,nums,int,right,&&,code.18,leetcode,left
来源: https://www.cnblogs.com/15078480385zyc/p/16483742.html