Advertisement
sweet1cris

Untitled

Jan 9th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.05 KB | None | 0 0
  1. public class Solution {
  2.     public List<List<Integer>> fourSum(int[] num, int target) {
  3.         List<List<Integer>> rst = new ArrayList<List<Integer>>();
  4.         Arrays.sort(num);
  5.  
  6.         for (int i = 0; i < num.length - 3; i++) {
  7.             if (i != 0 && num[i] == num[i - 1]) {
  8.                 continue;
  9.             }
  10.  
  11.             for (int j = i + 1; j < num.length - 2; j++) {
  12.                 if (j != i + 1 && num[j] == num[j - 1])
  13.                     continue;
  14.  
  15.                 int left = j + 1;
  16.                 int right = num.length - 1;
  17.                 while (left < right) {
  18.                     int sum = num[i] + num[j] + num[left] + num[right];
  19.                     if (sum < target) {
  20.                         left++;
  21.                     } else if (sum > target) {
  22.                         right--;
  23.                     } else {
  24.                         ArrayList<Integer> tmp = new ArrayList<Integer>();
  25.                         tmp.add(num[i]);
  26.                         tmp.add(num[j]);
  27.                         tmp.add(num[left]);
  28.                         tmp.add(num[right]);
  29.                         rst.add(tmp);
  30.                         left++;
  31.                         right--;
  32.                         while (left < right && num[left] == num[left - 1]) {
  33.                             left++;
  34.                         }
  35.                         while (left < right && num[right] == num[right + 1]) {
  36.                             right--;
  37.                         }
  38.                     }
  39.                 }
  40.             }
  41.         }
  42.  
  43.         return rst;
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement