首页 > 编程语言 > 详细

16. 3Sum Closest (JAVA)

时间:2019-04-25 23:11:46      阅读:142      评论:0      收藏:0      [点我收藏+]

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:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

 

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        if(nums.length<3) return 0;

        int sum;
        int ret=nums[0]+nums[1]+nums[2]; //initialize return value
        int len = nums.length-2;
        int left; //point to the left side of the array
        int right; //point to the right side of the array
        
        Arrays.sort(nums);
        
        for(int i = 0; i < len; i++){
            left = i+1;
            right = len+1;
            
            while(left < right){
                sum = nums[i] + nums[left] + nums[right];
                if(sum > target){
                    right--;
                }
                else if(sum < target){
                    left++;
                }
                else{
                    return target;
                }
                
                if(Math.abs(target - sum) < Math.abs(target - ret)) ret = sum;
            }
            
            //skip repeated digital
            while(nums[i] == nums[i+1]) {
                if(i+1 >= len) break;
                i++; 
            }
        }
        return ret;
    }
}

 

16. 3Sum Closest (JAVA)

原文:https://www.cnblogs.com/qionglouyuyu/p/10771678.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!