zoukankan      html  css  js  c++  java
  • [LeetCode] 16. 3Sum Closest

    Given an array nums of n integers 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).

    Constraints:

    • 3 <= nums.length <= 10^3
    • -10^3 <= nums[i] <= 10^3
    • -10^4 <= target <= 10^4

    最近三数之和。题意是给一个数组和一个target数字,返回一个三数之和使得nums[A] + nums[B] + nums[C] = target或尽可能接近target。

    思路跟15题类似,也是需要先排序。排序之后,先固定第一个数字,然后后两个数字之间做two pointer逼近。逼近的方式是如果

    res = nums[A] + nums[B] + nums[C] = target,则直接返回这个res;

    如果res大于target,C--

    如果res小于target,B++

    时间O(n^2)

    空间O(1)

    JavaScript实现

     1 /**
     2  * @param {number[]} nums
     3  * @param {number} target
     4  * @return {number}
     5  */
     6 var threeSumClosest = function(nums, target) {
     7     nums = nums.sort((a, b) => a - b);
     8     const len = nums.length;
     9     let res = nums[0] + nums[1] + nums[len - 1];
    10     let low, high, sum;
    11     for (let i = 0; i < nums.length - 2; i++) {
    12         low = i + 1;
    13         high = nums.length - 1;
    14         while (low < high) {
    15             sum = nums[i] + nums[low] + nums[high];
    16             if (Math.abs(target - sum) < Math.abs(target - res)) {
    17                 res = sum;
    18             }
    19             if (sum > target) {
    20                 high--;
    21             } else {
    22                 low++;
    23             }
    24         }
    25     }
    26     return res;
    27 };

    Java实现

     1 class Solution {
     2     public int threeSumClosest(int[] nums, int target) {
     3         int res = nums[0] + nums[1] + nums[nums.length - 1];
     4         Arrays.sort(nums);
     5 
     6         for (int i = 0; i < nums.length - 2; i++) {
     7             int start = i + 1;
     8             int end = nums.length - 1;
     9             while (start < end) {
    10                 int sum = nums[i] + nums[start] + nums[end];
    11                 if (sum > target) {
    12                     end--;
    13                 } else {
    14                     start++;
    15                 }
    16                 if (Math.abs(target - sum) < Math.abs(target - res)) {
    17                     res = sum;
    18                 }
    19             }
    20         }
    21         return res;
    22     }
    23 }

    LeetCode 题目总结

  • 相关阅读:
    机器不学习:如何处理数据中的「类别不平衡」?
    机器不学习:一种提升预测能力的方法-机器学习模型
    机器不学习:CNN 入门讲解1-什么是卷积
    机器不学习:浅析深度学习在实体识别和关系抽取中的应用
    机器不学习:用神经模块网络学习推理
    机器不学习:初识迁移学习
    机器不学习:一文彻底读懂智能对话系统
    跟随鼠标的div
    回到顶部的流畅滚动——scrollTop
    js学习小笔记
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11846698.html
Copyright © 2011-2022 走看看