15.3Sum

作者: 一棵会开花的树_f654 | 来源:发表于2018-01-20 09:53 被阅读0次

问题描述:
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]
]

这道题用到了List,鉴于很久没接触Java了,这道题没有自己独立完成,其实想了想,要是我自己写的话,应该是这么个思路:三重循环,计算三个数的和是否为target,但看了别人的高效代码后,觉得这样直接写应该会产生重复的结果。
先上代码吧:

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);  //先给数组排序,方便后续程序的进行
        for (int i = 0; i + 2 < nums.length; i++) {
            if(i>0 && nums[i]==nums[i-1]) continue;  //防止重复的结果
            int j = i+1;
            int k = nums.length-1;
            int target = -nums[i];
            while(j<k){
                if(nums[j]+nums[k] == target){
                    res.add(Arrays.asList(nums[i],nums[j],nums[k]));
                    j++;
                    k--;
                    while(j<k && nums[j]==nums[j-1]) j++;  //防止重复的结果
                    while(j<k && nums[k]==nums[k+1]) k--;  //防止重复的结果
                    
                }else if(nums[j]+nums[k] > target){
                    k--;
                }
                else{
                    j++;
                }
            }
        }
        return res;
    }
}

涉及到的Java知识:
Arrays.asList() 是将数组作为列表

相关文章

  • Day2

    15.3Sum Given an array S of n integers, are there element...

  • 15.3Sum

    问题描述:Given an array S of n integers, are there elements a...

  • LeetCodeSwift 15.3Sum - 三数之和

    题目 三数之和 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 ...

网友评论

      本文标题:15.3Sum

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