Advertisement
Guest User

3Sum

a guest
Jun 26th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.22 KB | None | 0 0
  1. Find unique 3sum: https://oj.leetcode.com/problems/3sum/
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class Solution {
  6.    
  7.     public List<List<Integer>> threeSum(int[] num, int k) {
  8.         List<List<Integer>> result = new ArrayList();
  9.         if(num.length < 3) return result;
  10.        
  11.         Arrays.sort(num);      
  12.         for(int i = 0; i < num.length; i ++) {
  13.             if(i > 0 && num[i] == num[i-1]) continue;
  14.             int target = k - num[i];
  15.             for(int m = i + 1, n = num.length - 1; m < n;) {
  16.                 int sum = num[m] + num[n];
  17.                 if( sum == target) {
  18.                     List<Integer> list = new ArrayList();
  19.                     list.add(num[i]);
  20.                     list.add(num[m]);
  21.                     list.add(num[n]);
  22.                     result.add(list);
  23.                     do { m ++; } while(m < n && num[m] == num[m - 1]);
  24.                     do { n --; } while(m < n && num[n] == num[n + 1]);
  25.                 } else if(sum > target)
  26.                     do { n --; } while(m < n && num[n] == num[n + 1]);
  27.                   else
  28.                     do { m ++; } while(m < n && num[m] == num[m - 1]);                
  29.             }
  30.         }
  31.         return result;
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement