3Sum Closest
2016-06-27 23:28
295 查看
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.
2.解题思路
这道题目和3Sum的题目基本一致,解题方法也大体相同,只是需要注意一些细节即可。3Sum的具体解决方法参见我的另一篇文章THREE SUM。
首先将原数组进行排序,得到有序数组,然后建立一个从头遍历到结尾的循环,在此循环过程中,从第二个位置和最后一个位置开始夹逼,求出这三个数的和tmpSum,每次求tmpSum与target求差tmpMin,如果abs(tmpMin)小于初试的最小值min,则对min进行更新,知道遍历结束,rslt中保存了最接近的和,min中保存了最小差的绝对值,最后返回。整个过程算法复杂度为O(n^2)
3.代码实现:
如果不会这个问题的话,可以仔细看看我上篇文章对于3Sum问题的求解过程,而3Sum的求解过程又来自于2Sum,解决了2Sum的问题,就可以解决3Sum的问题了。
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).
2.解题思路
这道题目和3Sum的题目基本一致,解题方法也大体相同,只是需要注意一些细节即可。3Sum的具体解决方法参见我的另一篇文章THREE SUM。
首先将原数组进行排序,得到有序数组,然后建立一个从头遍历到结尾的循环,在此循环过程中,从第二个位置和最后一个位置开始夹逼,求出这三个数的和tmpSum,每次求tmpSum与target求差tmpMin,如果abs(tmpMin)小于初试的最小值min,则对min进行更新,知道遍历结束,rslt中保存了最接近的和,min中保存了最小差的绝对值,最后返回。整个过程算法复杂度为O(n^2)
3.代码实现:
class Solution { public: //该函数返回一个数的绝对值 template<typename T> T abs(const T t) { if (t >= 0) return t; else return -t; } //返回最近接的和 int threeSumClosest(std::vector<int>& nums, int target) { if (nums.size() < 3) return 0; //排序 sort(nums.begin(), nums.end()); int rslt = nums.at(0)+ nums.at(1)+nums.at(2); auto it1 = nums.begin(); //min保存最小值 int min = abs(rslt - target); while (it1 != nums.end() - 1) { auto it2 = it1 + 1; auto it3 = nums.end() - 1; while (it2 < it3) { int tmpSum = *it1 + *it2 + *it3; int tmpMin = tmpSum - target; if (tmpSum < target) ++it2; else if (tmpSum == target) return target; else --it3; //判断是否更新 if (abs(tmpMin) < min) { min = abs(tmpMin); rslt = tmpSum; } } ++it1; } return rslt; } };4.总结
如果不会这个问题的话,可以仔细看看我上篇文章对于3Sum问题的求解过程,而3Sum的求解过程又来自于2Sum,解决了2Sum的问题,就可以解决3Sum的问题了。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解