`

Leetcode - 3Sum Closest

 
阅读更多
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).

[分析] 基于 3 sum的思路求解,先排序,选定第一个元素,然后夹逼法求出当前第一个元素下最接近target的 sum3。注意到closest初始化不要写成整数的最大最小值,不然比较获取局部最优时(if (Math.abs(sum3 - target) < Math.abs(closest - target)))会溢出导致错误结果。

public int threeSumClosest(int[] nums, int target) {
        if (nums == null || nums.length < 3)
            return Integer.MAX_VALUE;
        int N = nums.length;
        Arrays.sort(nums);
        int closest = nums[0] + nums[1] + nums[2];
        int sum3;
        for (int k = 0; k < N - 2; k++) {
            if (k > 0 && nums[k] == nums[k - 1])
                continue;
            int i = k + 1, j = N - 1;
            while (i < j) {
                sum3 = nums[i] + nums[j] + nums[k];
                if (sum3 == target) {
                    return target;
                } else if (sum3 > target) {
                    if (Math.abs(sum3 - target) < Math.abs(closest - target))
                        closest = sum3;
                    while (i < --j && nums[j] == nums[j + 1]);
                } else {
                    if (Math.abs(sum3 - target) < Math.abs(closest - target))
                        closest = sum3;
                    while (++i < j && nums[i] == nums[i - 1]);
                }
            }
        }
        return closest;
    }
分享到:
评论

相关推荐

    lrucacheleetcode-Leetcode-Practice:私人LeetCode练习代码库

    3sum-closest 49组字谜 更新 2020-1-16 123 已完成问题447 个回旋镖 更新 2020-1-17 124 已完成问题149 最大单线点数 更新 2020-1-18 126题已完成 56 个合并间隔 86 分区列表 98 验证二进制搜索树 9 审查问题 第105...

    javalruleetcode-LeetCode::lollipop:个人LeetCode习题解答仓库-多语言

    java lru leetcode :ice_cream: ...Closest 20 Valid Parentheses 26 Remove Duplicates from Sorted Array 48 Rotate Image 53 Maximum Subarray 55 Jump Game 56 Merge Intervals 64 Minimum Path Sum 73

    leetcode答案-LeetCode_1_TwoSum:LeetCode_1_TwoSum

    答案LeetCode_1_TwoSum LeetCode 问题:给定一个整数数组,找出两个数字,使它们相加为特定的目标数字。 函数 twoSum 应该返回两个数字的索引,使它们相加为目标,其中 index1 必须小于 index2。 请注意,您返回的...

    LeetCode最全代码

    16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [C++](./C++/3sum-closest.cpp) [Python](./Python/3sum-closest.py) | _O(n^2)_ | _O(1)_ | Medium || Two Pointers 18| [4 Sum]...

    leetcode和oj-LeetCode:力码

    leetcode 和 oj #问题列表(按标题升序) 标题|添加日期|AC 利率 ---|---|---|--- 3Sum |2012-01-17|16.4% 3Sum Closest|2012-01-18|26.8% 4Sum|2012-01-26 |21.3% 二进制加法|2012-04-02|25.6% 两个数相加|2011-11-...

    leetcode题库-LeetCode:力码

    leetcode题库 LeetCode 题解合集 本仓库展示了LeetCode题库中部分题目的解法(持续更新),所有代码均采用C++编写...3Sum.cpp 最接近的三数之和 3Sum Closest .cpp 20 有效的括号 Valid Parentheses.cpp 22 括号生成 G

    leetcode338-LeetCode:LeetCode刷题总结

    LeetCode刷题总结 1.Two Sum 2.Add Two Numbers 3.Longest Substring Without Repeating Characters 4.Median of Two Sorted Arrays 5.Longest Palindromic Substring (Manacher算法待完成) 6.ZigZag Conversion 7....

    leetcode2sumc-LeetCode_record:Leetcode问题我已经完成了解决方案和简要说明

    leetcode 2 和 c LeetCode_record(C++) Leetcode 问题 我已经完成了解决方案和简要说明。 目前,我正在做热门面试问题。 完毕 ...15-3总和 16-3Sum Closest(无解,类似3Sum) 454-4和II 正在做 18-4和

    程序员面试宝典LeetCode刷题手册

    16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Merge k Sorted ...

    leetcode530-algorithm:算法

    leetcode 530 ** LeetCode ...3Sum 016 3Sum Closest 017 Letter Combinations of a Phone Number 018 4Sum 020 Valid Parentheses 022 Generate Parentheses 028 Implement strStr() 031 Next Permutat

    leetcode2sumc-leetcode:JavaScript版本leetcode中文版代码

    leetcode 2 sum c leetcode 力扣(Leetcode)编程题,JavaScript版本。 编号 中文题目 ...3Sum 中等 16 3Sum Closest 中等 17 Letter Combinations of a Phone Number DFS 中等 18 4Sum 中等 19 Remo

    leetcode中文版-leetcode:leetcode

    3sum_closest 4sum 添加二进制 添加数字 添加字符串 add_two_numbers balance_binary_tree best_time_to_buy_and_sell_stock best_time_to_buy_and_sell_stock_II binary_tree_inorder_traversal binary_tree_level_...

    leetcode中文版-LeetCode:LeetcodeC++/Java

    leetcode中文版 LeetCode # Title Chinese Tag Solution 1 Two Sum 两数之和 array,hash ...3 ...3Sum Closest 最接近的三数之和 two pointers,array 21 Merge Two Sorted Lists 合并两个有序链表 lin

    leetcode2sumc-Leetcode_imp_C:Leetcode在C上的实现

    leetcode_0016_three_sum_closest.c leetcode_0018_four_sum.c : not ready leetcode_0026_remove_duplicates.c 27, 80, 283 leetcode_0031_next_permutation.c leetcode_0033_search_rotate.c : binary ...

    leetcode卡-LeetCodeMing:ARTS之Leetcode记录

    leetcode卡 LeetCodeMing 记录自己日常刷题LeetCode的点滴,技术改变世界,FOR PEACE 同时也是在参与ARTS打卡计划,记录自己的日常 LeetCodeMing ...Closest 18.4Sum Other 306.Additive Number [官网链接] ()

    LeetCode 最接近的三数之和

    题目来源:https://leetcode-cn.com/problems/3sum-closest 题目 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组...

    javalruleetcode-leetcode_js:Javascript中的LeetCode解决方案

    3Sum.js 16 3Sum Closest.js 电话号码的 17 个字母组合.js 19 从 List.js 的末尾删除第 N 个节点 20 个有效括号.js 21 合并两个有序Lists.js 22 生成括号.js 23 合并 k 排序 Lists.js Pairs.js 中的 24 个交换节点 k...

    lrucacheleetcode-LeetCode:这个库用于总结leetcode中遇到的习题,期望按照数据结构和常用方法分成2类,进行总结,

    lru cache ...3Sum Hash法转换2sum 9 3Sum Closest Sort +夹逼法 10 4Sum Sort +夹逼法 11 Remove Element 12 Next Permutation 公式 13 Permutation Sequence 公式 14 Valid Sudoku 15 Trapping Rain W

    Coding Interview In Java

    18 3Sum Closest 57 19 String to Integer (atoi) 59 20 Merge Sorted Array 61 ... ... 231 Counting Bits 561 232 Maximum Product of Word Lengths 563 233 Gray Code 565 234 Permutations 567 235 Permutations...

    gasstationleetcode-rust-leetcode:练习使用rust语言刷leetcode算法题目

    gas station ...p0016_3sum_closest; // pub mod p0018_4sum; pub mod p0003_longest_substring_without_repeating_characters; pub mod p0005_longest_palindromic_substring; pub mod p0007_reverse_int

Global site tag (gtag.js) - Google Analytics