码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 3Sum Closest

时间:2015-06-10 23:53:28      阅读:134      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!