标签:The public tco 更新 while 些许 排序 pos logs
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).
【题解】:这个题我是真的卡了好几天,主要是因为上一道题没用用指针的方式搜索也过了。。。可以去看我上一道题的题解,这个题,很关键的理解点是,要把数据进行排序,然后再固定一个数,另外两个数就可以通过指针的方式搜索了
这道题让我们求最接近给定值的三数之和,是在之前那道 3Sum 的基础上又增加了些许难度,那么这道题让我们返回这个最接近于给定值的值,即我们要保证当前三数和跟给定值之间的差的绝对值最小,所以我们需要定义一个变量 diff 用来记录差的绝对值,然后我们还是要先将数组排个序,然后开始遍历数组,思路跟那道三数之和很相似,都是先确定一个数,然后用两个指针 left 和 right 来滑动寻找另外两个数,每确定两个数,我们求出此三数之和,然后算和给定值的差的绝对值存在 newDiff 中,然后和 diff 比较并更新 diff 和结果 closest 即可,代码如下:
1 class Solution { 2 public: 3 int threeSumClosest(vector<int>& nums, int target) { 4 int diff = numeric_limits<int>::max(); 5 int Final; 6 sort(nums.begin(),nums.end()); 7 for(int i = 0; i < nums.size()-2; i++){ 8 int tm1 = nums[i]; 9 int left = i+1; int right = nums.size()-1; 10 while(left<right){ 11 int sum = tm1+nums[left]+nums[right]; 12 if(abs(target-sum) < diff){ 13 diff = abs(target-sum) ; 14 Final = sum; 15 } 16 if(target==sum) return target; 17 else if(target < sum) right--; 18 else left++; 19 } 20 } 21 return Final; 22 } 23 };
Leetcode 16. 3Sum Closest(指针搜索)
标签:The public tco 更新 while 些许 排序 pos logs
原文地址:https://www.cnblogs.com/shanyr/p/11506172.html