本文主要是介绍LeetCode 16.3Sum Closest,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
思路:
- 初始状态
2.三数之和小于target
3.三数之和大于target
4.second和third相遇后first++
5.末尾状态
class Solution {
public:int threeSumClosest(vector<int>& nums, int target) {int minVal = 2147483647;int m = 0, n = 0, r = 0;sort(nums.begin(), nums.end());for (int i = 0; i < nums.size(); ++i) {for (int j = i + 1, k = nums.size() - 1; j < k; ) {if (nums[i] + nums[j] + nums[k] == target) {return target;}else if(nums[i] + nums[j] + nums[k] > target) {if (minVal > abs(nums[i] + nums[j] + nums[k] - target)) {minVal = abs(nums[i] + nums[j] + nums[k] - target);m = i;n = j;r = k;}--k;}else {if (minVal > abs(nums[i] + nums[j] + nums[k] - target)) {minVal = abs(nums[i] + nums[j] + nums[k] - target);m = i;n = j;r = k;}++j;}}}return nums[m] + nums[n] + nums[r];}
};
这篇关于LeetCode 16.3Sum Closest的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!