标签:
public class Solution { public ArrayList<ArrayList<Integer>> threeSum(int[] nums) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if (nums == null || nums.length < 3) { return res; } for (int i = 0; i < nums.length-2; i++) { if (i != 0 && nums[i] == nums[i - 1]) { continue; }//to skip duplicate numbers [0,0,0,0] int left = i+1; int right = nums.length - 1; Arrays.sort(nums); while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum == 0) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(nums[i]); arr.add(nums[left]); arr.add(nums[right]); res.add(arr); left++; right--; while (left < right && nums[left] == nums[left - 1]) { left++; }//to skip duplicates while (left < right && nums[right] == nums[right + 1]) { right--; }//to skip duplicates } else if (sum < 0) { left++; } else { right--; } } } return res; } }
注意排除重复。
标签:
原文地址:http://www.cnblogs.com/77rousongpai/p/4513527.html