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

leetcode | 3Sum Closest

时间:2015-05-26 21:36:09      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:leetcode   array   sum   

3Sum Closest : https://leetcode.com/problems/3sum-closest/

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

解析:
根据上一题 3 Sum 中的夹逼算法,可解此题。
不同的是无需考虑是否有重复的三个元素组,因为无需记录最接近target的元素组成

#include <vector>
#include <iostream>
#include <stdlib.h>
#include <algorithm>
using namespace std;

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int result = nums[0]+nums[1]+nums[2];//初始化
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size()-2; i++) {
            int j = i+1;
            int k = nums.size()-1;
            int sum;
            while (j < k) {
                sum = nums[i]+nums[j]+nums[k];
                if (abs(sum-target) < abs(result-target))
                    result = sum;
                if (sum < target)
                    j++;  //不需检测nums[j]==nums[j-1],可以重复,不需保存满足条件的元素
                else if (sum > target)
                    k--;
                else
                    return target;
            }
            //注:不可将第18、19行放在此处,因为此处的终止条件是j == k
        }
        return result;  
    }
};

int main()
{
    int num[] = {87,6,-100,-19,10,-8,-58,56};
    vector<int> nums(num, num+sizeof(num)/sizeof(num[0]));
    Solution sol;
    cout << sol.threeSumClosest(nums, 10) << endl;  //87 -19 -58 : 10
    cout << sol.threeSumClosest(nums, 9) << endl;  //87 -19 -58 : 10
    cout << sol.threeSumClosest(nums, 8) << endl; 
    getchar();
}

leetcode | 3Sum Closest

标签:leetcode   array   sum   

原文地址:http://blog.csdn.net/quzhongxin/article/details/46010781

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