Advertisement
aero2146

Three sum

Dec 29th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. class Solution {
  2.     public List<List<Integer>> threeSum(int[] nums) {
  3.         List<List<Integer>> result = new ArrayList<List<Integer>>();
  4.         Arrays.sort(nums);
  5.  
  6.         int i = 0;
  7.         while (i < nums.length) {
  8.           int l = i+1;
  9.           int r = nums.length - 1;
  10.  
  11.           if (i>0 && nums[i] == nums[i-1]) {
  12.             i++;
  13.             continue;
  14.           }
  15.  
  16.           while (l < r) {
  17.             int sum = nums[i] + nums[l] + nums[r];
  18.             if (sum == 0) {
  19.               List<Integer> tmpList = new ArrayList<Integer>();
  20.               tmpList.add(nums[i]);
  21.               tmpList.add(nums[l]);
  22.               tmpList.add(nums[r]);
  23.               result.add(tmpList);
  24.               while (l < r && nums[l] == nums[l+1]) l += 1;
  25.               while (l < r && nums[r] == nums[r-1]) r -= 1;
  26.               l += 1;
  27.               r -= 1;
  28.             }
  29.             else if (sum < 0) l += 1;
  30.             else r -= 1;
  31.           }
  32.           i++;
  33.         }
  34.         return result;
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement