#include <vector> #include <algorithm> #include <iostream> #include <cmath> #include <unordered_map> using namespace std; class Solution { public: Solution(){} ~Solution(){} int threeSumClosest(vector<int>& nums, int target) { //先对数组进行排序 sort(nums.begin(),nums.end()); int len=nums.size(); int left; int right; int min=0x7FFFFFFF; unordered_map<int,int>map; for (int i = 0; i < len; i++) { //左指针 left=i+1; //右指针 right=len-1; while (left<right) { int temp=nums[left]+nums[right]+nums[i]; if(temp==target){ return temp; } //当前和小于target,则左指针加1 if (temp<target) { left=left+1; }else{//当前和大于target,则右指针减1 right=right-1; } //绝对值判断是否接近 if (abs(target-temp)<min) { min=abs(target-temp); map.insert(make_pair(min,temp)); } } } //用map查出最小绝对值所对应的和 return map[min]; } }; int main(){ Solution s; vector<int> v{0,3,97,102,200}; cout<<s.threeSumClosest(v,300); return 0; }
标签:nums,int,三数,16,Solution,len,include,接近,left From: https://www.cnblogs.com/Yshun/p/16930180.html