1. 程式人生 > >lintCode 58. 四數之和

lintCode 58. 四數之和

  public List<List<Integer>> fourSum(int[] numbers, int target) {
        // write your code here
        Arrays.sort(numbers);
        List<List<Integer>> list = new ArrayList<>();
        int i = 0,j=0;
        for(i=0;i<numbers.length-3;i++){
            j=i+1;
            while
(j<numbers.length-2){ int left = j+1,right = numbers.length-1; while(left<right){ int sum = numbers[i]+numbers[j]+numbers[left]+numbers[right]; if(sum==target){ list.add(Arrays.asList(numbers[i],numbers[j],numbers[left++],numbers[right--])); while
(left<right&&numbers[left]==numbers[left-1]){ ++left; } while(left<right&&numbers[right]==numbers[right+1]){ --right; } }else if(sum<target){ ++left; }else
{ --right; } } while(numbers[j]==numbers[++j]&&j<numbers.length-1); } while(i<numbers.length-1&&numbers[i]==numbers[i+1]){ i++; } } return list; }