首页 > 其他 > 详细

[LeetCode] 3Sum Closest

时间:2015-06-10 23:52:24      阅读:297      评论:0      收藏:0      [点我收藏+]

This problem is very similar to 3Sum. You only need to maintain a variable for the sum that is closet to target. Also, some corner cases need to be handled; for example, nums does not have more than 2 elements.

The code is as follows, which is quite self-explanatory.

 1     int threeSumClosest(vector<int>& nums, int target) {
 2         sort(nums.begin(), nums.end());
 3         while (nums.size() <= 2)
 4             return accumulate(nums.begin(), nums.end(), 0);
 5         int ans = nums[0] + nums[1] + nums[2];
 6         for (int i = 0; i < nums.size() - 2; i++) {
 7             int left = i + 1, right = nums.size() - 1;
 8             while (left < right) {
 9                 int temp = nums[i] + nums[left] + nums[right];
10                 if (abs(temp - target) < abs(ans - target))
11                     ans = temp;
12                 if (temp == target) return ans;
13                 if (temp > target) right--;
14                 else left++;
15             }
16         }
17         return ans;
18     }

[LeetCode] 3Sum Closest

原文:http://www.cnblogs.com/jcliBlogger/p/4567740.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!