public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums == null || nums.length < 3) {
return result;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int start = i + 1;
int end = nums.length - 1;
while (start < end) {
if (nums[i] + nums[start] + nums[end] == 0) {
List<Integer> tmp = new ArrayList<Integer>();
tmp.add(nums[i]);
tmp.add(nums[start]);
tmp.add(nums[end]);
result.add(tmp);
start++;
end--;
while (start < end && nums[start] == nums[start - 1]) {
start++;
}
while (start < end && nums[end] == nums[end + 1]) {
end--;
}
} else if (nums[i] + nums[start] + nums[end] < 0) {
start++;
} else {
end--;
}
}
}
return result;
}
}
Too many edge cases, sucks :p
没有评论:
发表评论