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

LeetCode(16) 3Sum Closest

时间:2015-07-16 20:00:03      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

参考LeetCode(15) 3Sum

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {

        sort(nums.begin(), nums.end());

        int differ;
        int length = nums.size();
        bool mark = true;
        for(int i = 0; i < length - 2; i++) {

            int secondTarget = target - nums[i];
            int start = i + 1;
            int end = length - 1;
            for(; start < end; ) {

                if(mark) {

                    differ = nums[start] + nums[end] - secondTarget;

                    if(differ == 0) 

                        break;

                    mark = false;

                    if(nums[start] + nums[end] - secondTarget < 0)

                        start++;

                    if(nums[start] + nums[end] - secondTarget > 0)

                        end--;


                }else {

                    if(abs(nums[start] + nums[end] - secondTarget) < abs(differ))

                        differ = nums[start] + nums[end] - secondTarget;

                    if(differ == 0) 

                        break;

                    if(nums[start] + nums[end] - secondTarget < 0)

                        start++;

                    if(nums[start] + nums[end] - secondTarget > 0)

                        end--;

                }

            }

            if(differ == 0) 

                break;

        }

        return target + differ;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode(16) 3Sum Closest

标签:

原文地址:http://blog.csdn.net/guanzhongshan/article/details/46914101

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!