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:

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

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


 1 class Solution {
 2     public int threeSumClosest(int[] nums, int target) {
 3         int res = nums[0]+nums[1]+nums[2];
 4         Arrays.sort(nums);
 5         for(int i = 0 ; i<nums.length-2;i++){
 6             int lo=i+1,hi=nums.length-1;
 7             while(lo<hi){
 8                 int sum=nums[i]+nums[lo]+nums[hi];
 9                 if(sum>target) hi--;
10                 else lo++;
11                 if(Math.abs(sum-target)<Math.abs(res-target))
12                     res = sum;
13             }
14         }
15         return res;
16     }
17 }

猜你喜欢

转载自www.cnblogs.com/zle1992/p/9313719.html