首页 > 其他 > 详细

LeetCode(16) 3Sum Closest

时间:2015-07-16 19:59:48      阅读:148      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!