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 题目总结

  • 相关阅读:
    redis之windows安装
    ubuntu安装 ssh
    less乱码ESC显示问题
    linux 命令/目录 名称 英文单词 缩写 助记
    设计模式-策略模式
    设计模式-责任链模式
    ApplicationContexAware的作用
    ApplicationEvent事件机制
    mybatis注解版延迟加载、立即加载、一级缓存、二级缓存
    mybatis xml版延迟加载、立即加载、一级缓存、二级缓存
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11846698.html
Copyright © 2011-2022 走看看