首页 > 其他 > 详细

力扣(LeetCode)15. 三数之和

时间:2019-04-05 16:10:20      阅读:201      评论:0      收藏:0      [点我收藏+]

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]]

思路 用HashSet无重复的特点去重。

先将数组排序。 Arrays.sort(nums); //从小到大
用三个指针,i指向第一个元素,j指向第二个元素,k指向第三个元素。

java版

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        HashSet<List<Integer>> hashset = new HashSet<>();
 
        int i,j,k,len = nums.length;
        for(i=0;i<len-2;i++) {
            j = i+1;
            k = len-1;
            while(j < k) {
                int sum = nums[i]+nums[j]+nums[k];
                if(sum < 0) {
                    j++;
                }else if(sum > 0) {
                    k--;
                }else {
                    List<Integer> list1 = new ArrayList<>();
                    list1.add(nums[i]);
                    list1.add(nums[j]);
                    list1.add(nums[k]);
                    hashset.add(list1);
                   
                    j++;
                    k--;
                }
            }
        }
        if(hashset.size()!=0) {
            Iterator<List<Integer>> iterator = hashset.iterator();
            while(iterator.hasNext()) {
                list.add(iterator.next());
            }
        }
        return list;
    }
}

运行结果

技术分享图片

力扣(LeetCode)15. 三数之和

原文:https://www.cnblogs.com/lick468/p/10658788.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!