zoukankan      html  css  js  c++  java
  • LeetCode 16

    一、问题描述

    Description:

    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).

    给定一个包含 n 个整数的数组,以及一个目标整数 target,在数组中找出三个数,使它们的和 与 target 的距离最小。返回这三个数的和。

    假定每个输入一定有结果。


    二、解题报告

    同《LeetCode 15 - 3Sum》一样,本题我们也是要利用排序这个性质,来减少判断。

    思路:

    1. 先整体排一次序
    2. 然后遍历数组,固定一个元素,对其后的元素采用头尾指针。
    3. 若距离更小,更新距离与三个数之和。
    4. 否则,移动头指针或尾指针。

    时间复杂度是O(n2),代码如下:

    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            sort(nums.begin(), nums.end());      // 排序
    
            int distance = INT_MAX;              // 记录距离
            int sum = nums[0]+nums[1]+nums[2];   // 记录和
    
            for(int i=0; i<nums.size()-2; ++i) { // 固定一个数字
                int l = i+1;                     // 头指针
                int r = nums.size()-1;           // 尾指针
                while(l < r) {
                    // 如果距离更近,则更新
                    if(abs(nums[l]+nums[r]+nums[i]-target) < distance) {
                        sum = nums[l]+nums[r]+nums[i];
                        distance = abs(nums[l]+nums[r]+nums[i]-target);
                    }
    
                    if(nums[l]+nums[r]+nums[i] == target)
                        return sum;
                    else if(nums[l]+nums[r]+nums[i] < target)
                        ++l;
                    else
                        --r;
                }
            }
    
            return sum;
        }
    };

    AC 时间 20ms。





    LeetCode答案源代码:https://github.com/SongLee24/LeetCode


  • 相关阅读:
    oracle 导入数据语句
    移动上去换样式代码
    google suggest 代码例子
    删除一个表的字段的sql语句命令
    将json从前台传到后台注意问题
    eclipse 自动 getter setter 注释
    jsp界面获取地址栏参数
    常见的正则表达式验证
    JSTL 核心标签库
    javascript中的call和apply两个方法的区别
  • 原文地址:https://www.cnblogs.com/songlee/p/5738051.html
Copyright © 2011-2022 走看看