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;
    }
}

linm
1 声望4 粉丝

〜〜〜学习始于模仿,成长得于总结〜〜〜


下一篇 »
1. Two Sum