首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >LeetCode 16. 3sum

LeetCode 16. 3sum

作者头像
流川疯
发布2022-06-16 08:14:56
发布2022-06-16 08:14:56
23600
代码可运行
举报
运行总次数:0
代码可运行

文章大纲


题目简介与解题思路

题目简介

Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.

Return the sum of the three integers.

You may assume that each input would have exactly one solution.

Example 1:

Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2:

Input: nums = [0,0,0], target = 1 Output: 0

Constraints:

3 <= nums.length <= 1000 -1000 <= nums[i] <= 1000 -104 <= target <= 104

解法

主要的思路是排序后,移动两个指针的思路

Sort the vector and then no need to run O(N^3) algorithm as each index has a direction to move.

The code starts from this formation.

本题的解法不需要


/------------------------------------------------------------------- ^ ^ -------------------------------------------------------------- ^ | | --------------------------------------------------------------- | | ± second ------------------------------------------------- third ±first

if nums[first] + nums[second] + nums[third] is smaller than the target, we know we have to increase the sum. so only choice is moving the second index forward.


/-------------------------------------------------------------------- ^ ^ -------------------------------------------------------------- ^ | | ---------------------------------------------------------------- | | — ± second ---------------------------------------------- third ±first

if the sum is bigger than the target, we know that we need to reduce the sum. so only choice is moving ‘third’ to backward. of course if the sum equals to target, we can immediately return the sum.


/---------------------------------------------------------------------------- ^ ^ -------------------------------------------------------------- ^ | | ---------------------------------------------------------------- | | ± second ------------------------------------------------------- third ±first

when second and third cross, the round is done so start next round by moving ‘first’ and resetting second and third.


/--------------------------------------------------------------------- — ^ — ^--------------------------------------------------------- ^ — | ---- | --------------------------------------------------------- | — | ---- ± second ------------------------------------------- third — ±first

while doing this, collect the closest sum of each stage by calculating and comparing delta. Compare abs(target-newSum) and abs(target-closest). At the end of the process the three indexes will eventually be gathered at the end of the array.


----------------------------------------------------------------- ^ ^ ^ ------------------------------------------------------------------ | | `- third ------------------------------------------------------------------ | ± second ------------------------------------------------------------------ ±first

if no exactly matching sum has been found so far, the value in closest will be the answer.


c++ 代码

代码语言:javascript
代码运行次数:0
运行
复制
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int n = nums.size(), ans = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < n-2; ++i) {
            int l = i + 1, r = n - 1;
            while (l < r) {
                int sum3 = nums[i] + nums[l] + nums[r];
                if (abs(ans - target) > abs(sum3 - target)) // Update better ans
                    ans = sum3;
                if (sum3 == target) break;
                if (sum3 > target)
                    --r; // Sum3 is greater than the target, to minimize the difference, we have to decrease our sum3
                else
                    ++l; // Sum3 is lesser than the target, to minimize the difference, we have to increase our sum3
            }
        }
        return ans;
    }
};

scala 代码


python 代码

代码语言:javascript
代码运行次数:0
运行
复制
class Solution:
    def threeSumClosest(self, nums: [int], target: int) -> int:

        nums.sort()
        result = sum(nums[:3])

        for i in range(len(nums)):
            left,right = i+1,len(nums)-1
            while left < right:
                s = sum((nums[i],nums[left],nums[right]))
                if abs(s - target) < abs(result - target):
                    result = s
                if s < target:
                    left = left +1
                elif s> target:
                    right = right -1
                else:
                    return result

        return  result



if __name__ == "__main__":
    s = Solution()
    print(s.threeSumClosest([-1,2,1,-4],1))

参考文献

https://leetcode.com/problems/3sum-closest/

scala 版本题解 https://leetcode.com/problems/3sum-closest/discuss/?currentPage=1&orderBy=most_votes&query=&tag=scala

带有解释的题解 https://leetcode.com/problems/3sum-closest/discuss/7883/C%2B%2B-solution-O(n2)-using-sort

python 题解 2 个指针

https://leetcode.com/problems/3sum-closest/discuss/8026/Python-solution-(two-pointer).

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-06-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章大纲
  • 题目简介与解题思路
    • 题目简介
    • 解法
  • c++ 代码
  • scala 代码
  • python 代码
  • 参考文献
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档