每天一题LeetCode[第十四天]

来源:互联网 发布:淘宝模板怎么用 编辑:程序博客网 时间:2024/06/07 18:25

每天一题LeetCode[第十四天]


3 Sum Closest

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

翻译:

给一个整型数组,三个数之和为一组,找到最接近target的一组数之和,并将这个和返回。你可以认为每次输入的数据直邮一个确切答案例子:整型数组 {-1,2, 1,-4} target=1所以最佳答案为 2 因为 -1+2+1=2

解题思路:

  • 这一题一开始有点懵逼,后来会想到之前做的3 sum的题目,就大概有了思路了,类似把target =0 的情况 并且最佳条件为result-target 的最小值 从头遍历到尾,每次遍历设置两个指针,分别从头和尾开始。根据满足不同的条件那向中间逼近。很简单,tmpSum

Java代码:

public class Solution {    public int threeSumClosest(int [] num, int target){        int result=num[0]+num[1]+num[2];        int tmpSum=0;        Arrays.sort(num);        for(int i=0;i<num.length-2;i++){            int start=i+1,end=num.length-1;            while (start<end){                tmpSum=num[i]+num[start]+num[end];                if(tmpSum>target){                    end--;                }else if(tmpSum<target){                    start++;                }else{                    return tmpSum;                }                if(Math.abs(tmpSum-target)<Math.abs(result-target)){                    result=tmpSum;                }            }        }        return result;    }}

提高代码质量就是:积累精美的思路,优质的细节的过程。

0 0