本文主要是介绍LeedCode·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).
思路:
3-sum问题的简化版
代码:
class Solution {
public:int threeSumClosest(vector<int>& nums, int target) {if(nums.size() == 0)return 0;sort(nums.begin(), nums.end());int min_sum, min_dis = INT_MAX, cur_dis;for(int i = 0; i < nums.size()-2; ++i){for(int j=i+1, k=nums.size()-1; j < k; ){int sumv = nums[i]+nums[j]+nums[k];int res = sumv-target;cur_dis = abs(res);if(res == 0)return sumv;else if(res < 0)++j;else--k;if(cur_dis < min_dis){min_dis = cur_dis;min_sum = sumv;}}}return min_sum;}
};
结果:
这篇关于LeedCode·16. 3Sum Closest的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!