3Sum Closest
来源:互联网 发布:法兰克编程教学 编辑:程序博客网 时间:2024/05/20 20:45
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).
类似于3Sum的处理, 在处理3Sum的时候,是将所有满足条件的和都保存起来,在处理此问题的时候,则要求解每次twoSum中与curtarget差值最小的和,最后在外层循环再求与最终target差值最小的和
class Solution {public: //类似于3Sum的处理, 在处理3Sum的时候,是将所有满足条件的和都保存起来,在处理此问题的时候, //则要求解每次twoSum中与curtarget差值最小的和,最后在外层循环再求与最终target差值最小的和 int twoSum(vector<int> &nums, int n, int curStart, int curTarget) { int low = curStart, high = n - 1; int minDiff = 99999999; while(low < high) { int tmpSum = nums[low] + nums[high]; if( tmpSum == curTarget) { return tmpSum; } else if(tmpSum < curTarget) { int tmps = nums[low]; while(low < high && tmps == nums[low]) ++low; } else { int tmps = nums[high]; while(low < high && tmps == nums[high]) --high; } minDiff = abs(tmpSum - curTarget) < abs(minDiff - curTarget) ? tmpSum : minDiff; } return minDiff; } int threeSumClosest(vector<int>& nums, int target) { int len = nums.size(); if(len < 3) return 0; sort(nums.begin(), nums.end()); int minDiff = 99999999, i = 0; while(i < len) { int curTarget = target - nums[i]; int diff = twoSum(nums, len, i + 1, curTarget); minDiff = abs(minDiff - target) > abs(diff + nums[i] - target) ? diff + nums[i] : minDiff; int tmps = nums[i]; while(i < len && nums[i] == tmps) ++i; } return minDiff; }};
0 0
- 3 Sum & 3 Sum Closest
- 【Leetcode】3Sum Closest (Sum)
- LeetCode: 3 Sum Closest
- 3Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- leetcode002:3sum closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- [LeetCode] 3Sum Closest
- C程序的编译和链接
- 剑指Offer面试题18(Java版):树的子结构
- 如此抄袭Apps之OscHub(一)
- HttpClient使用详解
- MAT使用及OOM分析
- 3Sum Closest
- MeasureSpec学习
- JSP和El表达式和JSTL标签库使用
- MongoDB初探系列之四:MongoDB与Java共舞
- Reverse Words in a String
- 7月份,一个多月来的总结
- UIKit框架-11.控制器跳转(UIStoryboardSegue)
- 南极圈、百老汇、前橙会、离异、毕浪、盛斗士…… 抱团突围的“离职帮”
- 单链表的实现---数据结构学习(一)