LeetCode题解 第十五周

来源:互联网 发布:仿淘宝app模板 编辑:程序博客网 时间:2024/06/01 09:32

1.3Sum Closest

https://leetcode.com/problems/3sum-closest/description/


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.

Example:

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).


Difficulty:Medium

code:

class Solution {public:int threeSumClosest(vector<int>& nums, int target1) {vector<vector<int>> res;int min = INT_MAX;int targetsum;sort(nums.begin(), nums.end());for (int i = 0; i < nums.size(); i++){int target = target1-nums[i];int front = i + 1;int back = nums.size() - 1;while (front < back){int sum = nums[i] + nums[front] + nums[back];if (abs(sum - target1) < min){min = abs(sum - target1);targetsum = sum;}if (nums[front] + nums[back] < target){front++;}else if (nums[front] + nums[back] > target){back--;}else{return target1;}}while (i + 1 < nums.size() && nums[i] == nums[i + 1]){i++;}}return targetsum;}};


原创粉丝点击