资讯专栏INFORMATION COLUMN

[Leetcode] 3Sum 4Sum 3Sum Closet 多数和

trigkit4 / 2557人阅读

摘要:为了避免得到重复结果,我们不仅要跳过重复元素,而且要保证找的范围要是在我们最先选定的那个数之后的。而计算则同样是先选一个数,然后再剩下的数中计算。

2Sum

在分析多数和之前,请先看Two Sum的详解

3Sum

请参阅:https://yanjia.me/zh/2019/01/...

双指针法 复杂度

时间 O(N^2) 空间 O(1)

思路

3Sum其实可以转化成一个2Sum的题,我们先从数组中选一个数,并将目标数减去这个数,得到一个新目标数。然后再在剩下的数中找一对和是这个新目标数的数,其实就转化为2Sum了。为了避免得到重复结果,我们不仅要跳过重复元素,而且要保证2Sum找的范围要是在我们最先选定的那个数之后的。

代码
public class Solution {
    public List> threeSum(int[] nums) {
        Arrays.sort(nums);
        ArrayList> res = new ArrayList>();
        for(int i = 0; i < nums.length - 2; i++){
            // 跳过重复元素
            if(i > 0 && nums[i] == nums[i-1]) continue;
            // 计算2Sum
            ArrayList> curr = twoSum(nums, i, 0 - nums[i]);
            res.addAll(curr);
        }
        return res;
    }
    
    private ArrayList> twoSum(int[] nums, int i, int target){
        int left = i + 1, right = nums.length - 1;
        ArrayList> res = new ArrayList>();
        while(left < right){
            if(nums[left] + nums[right] == target){
                ArrayList curr = new ArrayList();
                curr.add(nums[i]);
                curr.add(nums[left]);
                curr.add(nums[right]);
                res.add(curr);
                do {
                    left++;
                }while(left < nums.length && nums[left] == nums[left-1]);
                do {
                    right--;
                } while(right >= 0 && nums[right] == nums[right+1]);
            } else if (nums[left] + nums[right] > target){
                right--;
            } else {
                left++;
            }
        }
        return res;
    }
}

2019/01
Go

func threeSum(nums []int) [][]int {
    // sort the slice to avoid duplicate and also use two pointers
    sort.Slice(nums, func(i, j int) bool {
        return nums[i] < nums[j]
    })
    res := [][]int{}
    for i := 0; i < len(nums); i++ {
        // skip duplicate numbers
        if i != 0 && nums[i] == nums[i - 1] {
            continue
        }
        // convert into a twoSum problem
        res = twoSum(nums, i + 1, nums[i], res)
    }
    return res
}

func twoSum(nums []int, start, first int, res [][]int) [][]int {
    left := start
    right := len(nums) - 1
    for left < right {
        sum := nums[left] + nums[right]
        if sum == 0 - first {
            res = append(res, []int{first, nums[left], nums[right]})
            left++
            right--
            // skip duplicate numbers from left side
            for left < len(nums) && left > 0 && nums[left] == nums[left - 1] {
                left++
            }
            // skip duplicate numbers from right side
            for right >= 0 && right < len(nums) - 1 && nums[right] == nums[right + 1] {
                right--
            }
        } else if sum > 0 - first {
            right--
        } else if sum < 0 - first {
            left++
        }
    }
    return res
}
4Sum 双指针法 复杂度

时间 O(N^3) 空间 O(1)

思路

和3Sum的思路一样,在计算4Sum时我们可以先选一个数,然后在剩下的数中计算3Sum。而计算3Sum则同样是先选一个数,然后再剩下的数中计算2Sum。

代码
public class Solution {
    public List> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        ArrayList> res = new ArrayList>();
        for(int i = 0; i < nums.length - 3; i++){
            if(i > 0 && nums[i] == nums[i-1]) continue;
            List> curr = threeSum(nums, i, target - nums[i]);
            res.addAll(curr);
        }
        return res;
    }
    
    private List> threeSum(int[] nums, int i, int target) {
        ArrayList> res = new ArrayList>();
        for(int j = i + 1; j < nums.length - 2; j++){
            if(j > i + 1 && nums[j] == nums[j-1]) continue;
            List> curr = twoSum(nums, i, j, target - nums[j]);
            res.addAll(curr);
        }
        return res;
    }
    
    private ArrayList> twoSum(int[] nums, int i, int j, int target){
        int left = j + 1, right = nums.length - 1;
        ArrayList> res = new ArrayList>();
        while(left < right){
            if(nums[left] + nums[right] == target){
                ArrayList curr = new ArrayList();
                curr.add(nums[i]);
                curr.add(nums[j]);
                curr.add(nums[left]);
                curr.add(nums[right]);
                res.add(curr);
                do {
                    left++;
                }while(left < nums.length && nums[left] == nums[left-1]);
                do {
                    right--;
                } while(right >= 0 && nums[right] == nums[right+1]);
            } else if (nums[left] + nums[right] > target){
                right--;
            } else {
                left++;
            }
        }
        return res;
    }
}
3Sum Closet
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

双指针法 复杂度

时间 O(N^2) 空间 O(1)

思路

和3Sum的解法一样。在3Sum中,我们只有找到和目标完全一样的时候才返回,但在Closet中,我们要记录一个最小的差值,并同时记录下这个最小差值所对应的和。

代码
public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int closetSum = 0, minDiff = Integer.MAX_VALUE / 2;
        for(int i = 0; i < nums.length; i++){
            int left = i + 1, right = nums.length - 1;
            while(left < right){
                // 当前组合的和
                int sum = nums[i] + nums[left] + nums[right];
                // 当前组合的和与目标的差值
                int diff = Math.abs(sum - target);
                // 如果差值更小则更新最接近的和
                if(diff < minDiff){
                    closetSum = sum;
                    minDiff = diff;
                }
                // 双指针的移动方法和3Sum一样
                if (sum < target){
                    left++;
                } else if (sum > target){
                    right--;
                } else {
                    return sum;
                }
            }
        }
        return closetSum;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64508.html

相关文章

  • [Leetcode] Two Sum, 3Sum,4Sum,4SumII,3Sum Closet

    摘要:解题思路题目要求两个数和等于,返回其题目说明不会有重复情况,所以我们一旦发现符合情况的,就可以直接结束循环并返回。特殊情况就是正好等于,那肯定是最接近的情况,直接返回即可。 Two SumGiven an array of integers, return indices of the two numbers such that they add up to a specific ta...

    EddieChan 评论0 收藏0
  • 【LC总结】K Sum (Two Sum I II/3Sum/4Sum/3Sum Closest)

    摘要:找符合条件的总数。双指针区间考虑边界,长度,为空,等。之后的范围用双指针和表示。若三个指针的数字之和为,加入结果数组。不要求,所以不用判断了。同理,头部两个指针向后推移,后面建立左右指针夹逼,找到四指针和为目标值的元素。 Two Sum Problem Given an array of integers, find two numbers such that they add up ...

    awesome23 评论0 收藏0
  • leetcode 18 4Sum

    摘要:题目详情输入一个长度为的整数数组和一个目标整数,我们需要找出是否存在个元素,使得的和等于。如果有,输出这样的非重复的元素序列。在求元素的时候可以通过左右指针减少查找时间。 题目详情 Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target...

    Vixb 评论0 收藏0
  • [LeetCode] 4Sum & 4Sum II

    摘要:和方法一样,多一个数,故多一层循环。完全一致,不再赘述, 4Sum Problem Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which ...

    sydMobile 评论0 收藏0
  • leetcode 部分解答索引(持续更新~)

    摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...

    leo108 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<