LeetCode随笔之Array

来源:互联网 发布:2014上半年经济数据 编辑:程序博客网 时间:2024/06/02 06:53

一. Array
1. 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).

**思路:先排序,然后按照顺序举出所有可能。
代码:**

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        sort(nums.begin(),nums.end());        int minDis=INT_MAX;        int out=0;        for(int i=0;i<nums.size()-2;i++){            int l=i+1,r=nums.size()-1;            while(l<r){                int sum=nums[i];                sum+=(nums[l]+nums[r]);                if(sum==target){out=target;return target;}                if(sum<target){l++;minDis=min(minDis,target-sum);if(minDis==target-sum)out=sum;}                if(sum>target){r--;minDis=min(minDis,sum-target);if(minDis==sum-target)out=sum;}            }        }        return out;    }};
原创粉丝点击