15. 3Sum

34次阅读

共计 980 个字符,预计需要花费 3 分钟才能阅读完成。

Given an array nums of n integers, are there elements a, b, c in nums 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.
Example:Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:[[-1, 0, 1], [-1, -1, 2]]
难度:medium
题目:给定一长度为 n 的数组,是否存在三元素之和为 0? 找出所有使其和为 0 的不同的三元组。
注意:返回的结果中不要含有重复元素。
思路:数组排序后使用双重循环固定一个值,再使内循环由两头向中间计算。
Runtime: 56 ms, faster than 52.39% of Java online submissions for 3Sum.
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (null == nums || nums.length < 1) {
return result;
}

Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n – 1; i++) {
if (i > 0 && nums[i] == nums[i – 1]) {
continue;
}
for (int left = i + 1, right = n – 1; left < right;) {
if (left > (i + 1) && nums[left] == nums[left – 1]) {
left++;
continue;
}
if (right < (n – 1) && nums[right] == nums[right + 1]) {
right–;
continue;
}
int sum = nums[i] + nums[left] + nums[right];
if (0 == sum) {
result.add(Arrays.asList(nums[i], nums[left++], nums[right–]));
} else if (sum > 0) {
right–;
} else {
left++;
}
}
}

return result;
}
}

正文完
 0