15. 3Sum

作者: 衣介书生 | 来源:发表于2018-04-10 21:39 被阅读16次

    题目分析

    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]
    ]
    

    解这道题目,首先我们将数组排序,然后从头开始遍历数组,将 3Sum 问题转成 Two Sum 问题。
    时间复杂度为O(n ^ 2)

    代码

    class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            // 只需要遍历到倒数第三个元素
            Arrays.sort(nums);
            for(int i = 0; i < nums.length - 2; i++) {
                if(i > 0 && nums[i] == nums[i - 1]) continue;
                // 问题转成了在 low 到 high 区间的 two sum 问题
                int low = i + 1, high = nums.length - 1, sum = 0 - nums[i];
                while(low < high) {
                    if(nums[low] + nums[high] == sum) {
                        res.add(Arrays.asList(nums[i], nums[low], nums[high]));
                        while(low < high && nums[low] == nums[low + 1]) low ++;
                        while(low < high && nums[high] == nums[high - 1]) high --;
                        low ++;
                        high --;
                    } else if(nums[low] + nums[high] < sum) {
                        low ++;
                    } else {
                        high --;
                    }
                }
            }
            return res;
        }
    }
    

    相关文章

      网友评论

          本文标题:15. 3Sum

          本文链接:https://www.haomeiwen.com/subject/bocohftx.html