[Day9]16. 3Sum Closest

For some emotional and schedule issues, I have been absent for two days. But there shouldn't be any excuse for this. So, I would make up as soon as possible!

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

ANALYSIS:
At beginning, I have no idea to solve this problem. So, I have to look the top solution.
And two days later, I borrow the thread and code on my own. Finally, AC!
The core idea: 'loop for the min number of three from 0 to length-1', 'use two point(so-called '游标') for middle number(starti) and max number(endi)', 'compare the abs of current sum and closest'

SOLUTION:

public static int threeSumClosest(int[] nums, int target) {
    Arrays.sort(nums);
    int closest=nums[0]+nums[1]+nums[2];
    for(int i=0;i<nums.length-2;i++){
        int starti=i+1;
        int endi=nums.length-1;
        int sum=nums[i]+nums[starti]+nums[endi];
        while(starti<endi){
            sum=nums[i]+nums[starti]+nums[endi];
            if(Math.abs(sum-target)<Math.abs(closest-target))
                closest=sum;
            if(sum==target)
                return target;
            else if(sum<target){
                starti++;
            }else if(sum>target){
                endi--;
            }
        }
    }
    return closest;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容