leetcode16 最接近的三数之和
作者:互联网
三个数循环太复杂
确定一个数,搜索另两个
先排序,之后就确定了搜索的策略
if(tp>target) while (l < r && nums[r] == nums[--r]); else if (tp<target) while (l < r && nums[l] == nums[++l]); else return target;
因为题目确定恰好有一组最优解,所以不用判断特殊情况
一旦temp=target,直接返回
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(),nums.end()); int ret=nums[0]+nums[1]+nums[2]; int len=nums.size(); int distance =abs(target-ret); if(ret==target) return target; for (int i = 0; i < len - 2; i++) { if(ret==target) return target; if((i>0)&&nums[i]==nums[i-1]) continue; int l = i + 1; int r = len - 1; while (l < r) { //多组 int tp = nums[i] + nums[l] + nums[r]; if (abs(target-tp) < distance){ ret=tp; distance=abs(target-tp); } if(tp>target) while (l < r && nums[r] == nums[--r]); else if (tp<target) while (l < r && nums[l] == nums[++l]); else return target; } } return ret; } };
标签:target,nums,int,三数,tp,abs,ret,leetcode16,接近 来源: https://www.cnblogs.com/lqerio/p/11755868.html