Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Find unique 3sum: https://oj.leetcode.com/problems/3sum/
- import java.util.Arrays;
- public class Solution {
- public List<List<Integer>> threeSum(int[] num, int k) {
- List<List<Integer>> result = new ArrayList();
- if(num.length < 3) return result;
- Arrays.sort(num);
- for(int i = 0; i < num.length; i ++) {
- if(i > 0 && num[i] == num[i-1]) continue;
- int target = k - num[i];
- for(int m = i + 1, n = num.length - 1; m < n;) {
- int sum = num[m] + num[n];
- if( sum == target) {
- List<Integer> list = new ArrayList();
- list.add(num[i]);
- list.add(num[m]);
- list.add(num[n]);
- result.add(list);
- do { m ++; } while(m < n && num[m] == num[m - 1]);
- do { n --; } while(m < n && num[n] == num[n + 1]);
- } else if(sum > target)
- do { n --; } while(m < n && num[n] == num[n + 1]);
- else
- do { m ++; } while(m < n && num[m] == num[m - 1]);
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement