标签:用法 tar end code 经典题目 res start null question
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
public class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums == null || nums.length == 0) { return result; } Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i++) { if (nums[i] > 0) { break; } if (i > 0 && nums[i] == nums[i - 1]) { continue; } int start = i + 1; int end = nums.length - 1; int target = 0 - nums[i]; while (start < end) { int tmp = nums[start] + nums[end]; if (tmp > target){ end--; } else if (tmp < target) { start++; } else { result.add(Arrays.asList(nums[i], nums[start], nums[end])); while (start < end && nums[start] == nums[start + 1]) { start++; } while (start < end && nums[end] == nums[end - 1]) { end--; } start++; end--; } } } return result; } }
标签:用法 tar end code 经典题目 res start null question
原文地址:http://www.cnblogs.com/aprilyang/p/6701897.html