阿翰剑指offer专项突破Day03数组(未完成)

阿翰剑指offer专项突破Day03数组(未完成),第1张

阿翰剑指offer专项突破Day03数组(未完成)

数组

1 数组中和为 0 的三个数

3  


数组 1 数组中和为 0 的三个数

剑指 Offer II 007. 数组中和为 0 的三个数https://leetcode-cn.com/problems/1fGaJU/

此题为「排序数组中两个数字之和」的加强版。

数组有有序的时候,固定一个i,在排序数组里找和为-i的数字即可,通过前一题,有了双指针寻找和为定值的O(n)方法,因此复杂度为O(n^2)。 由于题目给的不是排序的数组,排序算法的时间复杂度一般为O(nlogn),最后总时间复杂度为O(nlogn)+O(n^2),最后仍是O(n^2)。

注意:去重三元组

即找到一个符合要求的三元组后,既然是排序数组,可以通过一个temp值临时存储第一、二个值,两次循环判断直到不同再break,以过滤重复的数字。

class Solution {
    public List> threeSum(int[] nums) {
        List> result = new linkedList<>();
        if(nums.length >= 3){
            Arrays.sort(nums);
            int i = 0;
            while(i < nums.length - 2){
                twoSum(nums, i, result);
                int temp = nums[i];
                while(i < nums.length && nums[i] == temp)
                    ++i;
            }
        }
        return result;
    }
    public void twoSum(int[] nums, int i, List> result){
        int j = i + 1;
        int k = nums.length - 1;
        while(j < k){
            if(nums[i] + nums[j] + nums[k] == 0){
                result.add(Arrays.asList(nums[i], nums[j], nums[k]));
//                去重
                int temp = nums[j];
                while(nums[j] == temp && j < k){
                    ++j;
                }
            } else if (nums[i] + nums[j] + nums[k] < 0){
                ++j;
            } else{
                --k;
            }
        }
    }
}

3

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5713944.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存