LeetCode Top Interview Questions 16. 3Sum Closest (Java版; Medium)
题目描述
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).
//先对数组排序, 然后使用双指针; 核心: 双指针在有序数组上移动次数是O(N), 进而将本是O(N^2)的遍历转换成了O(N)的双指针移动classSolution{publicintthreeSumClosest(int[] nums,int target){
Arrays.sort(nums);int min = Integer.MAX_VALUE;int res =0;for(int i=0; i<=nums.length-3; i++){int cur = nums[i];//双指针, 首尾向中间移动;移动原则: sum>target时right--, sum<target时left++ 这个思路挺常用的, 但是没有理解透彻int left = i+1, right = nums.length-1;while(left<right){int sum = cur + nums[left]+ nums[right];//先判断是否需要更新resint gap = Math.abs(sum-target);//再调整双指针if(gap<min){
min = gap;
res = sum;}if(sum>target)
right--;elseif(sum<target)
left++;elsereturn sum;}}//看清楚了, 返回的是三个数的和return res;}}