15.三数之和

简介: 15.三数之和

在整数数组nums中,找3个元素(a+b+c)和为0的三元组。

方法1:暴力解法:三重循环 O(N^3) //超时

方法2:排序+双指针法  

先排序避免重复答案,降低复杂度变为twoSum,利用双指针找到所有解。

这里说的双指针法:a确定时,b+c 的值就确定为-a。 也就是随着b增加,c减少。那么b,c一共移动的次数是O(N)

    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        //先排序
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        //枚举a
        for (int first = 0; first < n; first++){
            //跳过重复的数
            if (first > 0 && nums[first] == nums[first -1] ) {
                continue;
            }
            //目标变成求和为-a 的twoSum问题
            int target = -nums[first];
            //c 在最右端
            int third = n - 1;
 
            //枚举 b
            for (int second = first + 1; second <n; second++) {
                if (second > first+1 && nums[second] == nums[second-1]) {
                    continue;
                }
                while (second<third && nums[second] + nums[third] > target) {
                    third--;
                }
                if (second == third) {
                    break;
                }
                if (nums[second] + nums[third] == target) {
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    ans.add(list);
                }
            }
        }
        return  ans;
 
 
    }
相关文章
|
8月前
|
算法
【算法专题突破】双指针 - 三数之和(7)
【算法专题突破】双指针 - 三数之和(7)
26 0
|
1月前
15. 三数之和
15. 三数之和
25 3
|
1月前
15.三数之和
15.三数之和
14 0
|
1月前
|
Java C++ Python
leetcode-15:三数之和
leetcode-15:三数之和
24 0
|
1月前
|
算法 C++
(C++)三数之和--双指针法
(C++)三数之和--双指针法
24 0
|
11月前
LeetCode: 16. 最接近的三数之和 | 双指针专题
【LeetCode: 16. 最接近的三数之和 | 双指针专题 】
41 1
|
算法 测试技术
leetcode:15.三数之和
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
61 0
|
存储
每日一题——三数之和(双指针)
每日一题——三数之和(双指针)
|
算法
LeetCode每日1题--三数之和
LeetCode每日1题--三数之和
62 0
|
测试技术 索引
leetcode_15. 三数之和
题目链接: 15. 三数之和 据说华为的机试经常考这题,而且这道题也是扩展性极强的一道题,你可以看到18. 四数之和,或者人为修改的五数之和,六数之和,乃至n 数之和,也就是
leetcode_15. 三数之和