LeetCode 15. 三数之和-java

LeetCode 15. 三数之和-java

原题链接

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

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

代码案例:1、输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
2、输入:nums = []
输出:[]

题解

class Solution {//双指针做法或者哈希表  双指针优先 双指针做法一定要有序
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> st = new ArrayList<List<Integer>>();
        //   List<List<Integer>> st = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        int n = nums.length;
        for(int i = 0; i < n ; i ++ ){//暴力做法是固定i 找到j
        if(nums[i] > 0) continue;//第一个数不能大于0
        if(i > 0 && nums[i] == nums[i-1]) continue;
            int j = i +1 , k = n -1 ;
            while(j < k ){
                int sum = nums[i]+nums[j]+nums[k];
                if(sum > 0 ){//说明k大了 
                    k--;
                    continue;
                }else if(sum < 0){//说明l小了
                    j++;
                    continue;
                }
                 //当等于0 的时候添加
            //st.add(new ArrayList<>(Array.aslist(nums[i],nums[j],nums[k])));
              st.add(Arrays.asList(nums[i],nums[j],nums[k]));
             //去除重复处理
                do {j ++;} while(j < k && nums[j] == nums[j - 1]);
                do {k --;} while(j < k && nums[k] == nums[k + 1]);
            }
           
        }
        return st;
    }
}
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
         List<List<Integer>> ans = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        int n = nums.length;
        for(int i = 0; i < n ; i ++ ){
            if(i > 0 && nums[i] == nums[i-1]) continue;
            for(int j = i + 1 , k = n -1 ; j < k ; j++){
                if(j > i+1 && nums[j] == nums[j-1]) continue;
                while(j < k -1 && nums[i]+nums[j]+nums[k-1] >= 0){//这里面k是下一个数
                    k--;
                }
                if(nums[i]+nums[j]+nums[k] == 0){
                    ans.add(Arrays.asList(nums[i],nums[j],nums[k]));
                }
            }
        }
        return ans ;
    }
}
posted @   依嘫  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示