15.三数之和

简介: 15.三数之和

image.png


方法一:暴力破解的方式


class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Set<List<Integer>> result=new HashSet<>();
        if(nums.length==0||nums==null){
            return new ArrayList<List<Integer>>();
        }
        Arrays.sort(nums);
        for(int i=0;i<nums.length-2;i++){
            for(int j=i+1;j<nums.length-1;j++){
                for(int k=j+1;k<nums.length;k++){
                    if(nums[i]+nums[j]+nums[k]==0){
                        List<Integer> temp=new ArrayList<>();
                        temp.add(nums[i]);
                        temp.add(nums[j]);
                        temp.add(nums[k]);
                        result.add(temp);
                    }
                }
            }
        }
        return  new ArrayList<List<Integer>>(result);
    }
}


方法二: 排序+双指针(去重)


class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> arr=new ArrayList<>();
        if(nums==null||nums.length<3){
            return arr;
        }
        Arrays.sort(nums);
        for(int i=0;i<nums.length;i++){
            int start=i+1;
            int end=nums.length-1;
            if(nums[i]>0){
                break;
            }
            //对于重复的条件进行判断
            if(i>0&&nums[i]==nums[i-1]){    //对i进行去重
                continue;
            }
            while(start<end){
                if(nums[i]+nums[start]+nums[end]==0){
                    List<Integer> temp=new ArrayList<Integer>();
                    temp.add(nums[i]);
                    temp.add(nums[start]);
                    temp.add(nums[end]);
                    arr.add(temp);
                     while(start<end&&nums[end]==nums[end-1]){  //对右侧进行去重
                        end--;
                    }
                     while(start<end&&nums[start]==nums[start+1]){   //对左侧进行去重
                        start++;
                    }
                    start++;
                    end--;
                }else if(nums[i]+nums[start]+nums[end]>0){
                    end--;
                }else{
                    start++;
                }
            }
        }
        return arr;
    }
}
目录
相关文章
|
8月前
|
算法
【算法专题突破】双指针 - 三数之和(7)
【算法专题突破】双指针 - 三数之和(7)
26 0
|
11天前
15.三数之和
15.三数之和
|
1月前
15. 三数之和
15. 三数之和
24 3
|
1月前
|
Java C++ Python
leetcode-15:三数之和
leetcode-15:三数之和
24 0
|
1月前
|
算法 C++
(C++)三数之和--双指针法
(C++)三数之和--双指针法
23 0
|
11月前
LeetCode: 16. 最接近的三数之和 | 双指针专题
【LeetCode: 16. 最接近的三数之和 | 双指针专题 】
40 1
|
算法 测试技术
leetcode:15.三数之和
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
60 0
|
测试技术 索引
leetcode_15. 三数之和
题目链接: 15. 三数之和 据说华为的机试经常考这题,而且这道题也是扩展性极强的一道题,你可以看到18. 四数之和,或者人为修改的五数之和,六数之和,乃至n 数之和,也就是
leetcode_15. 三数之和
|
Java C++ Python
【LeetCode】 15. 三数之和
第15题. 三数之和
59 0
【LeetCode】 15.  三数之和