LeetCode --- 16. 3Sum Closest
2015-01-30 21:29
260 查看
题目链接: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.
这道题的要求是在给定的正整数数组中,找到三个数,使其之和最接近给定的数字target,并返回这三个数字之和。可以假设每组输入有确切解。
这道题的思路和之前的Two Sum和3Sum差不多,简单方式是暴力查找,先排序,然后3层循环遍历数组,时间复杂度O(n3)。优化时,可以先固定一个数,再用两个指针l和r从这个数后面的两边往中间查找,逐个比较这三个数字之和与target的差距,记录最小的情况,当这三个数之和大于target的时候,r左移,而当之和小于target的时候,l右移,直到l和r相遇。这个其实就是在Two
Sum外层加1层循环,也和3Sum的复杂度一样,因此时间复杂度是排序的O(nlogn)加O(n2),即O(n2)。
时间复杂度:O(n2)
空间复杂度:O(1)
转载请说明出处:LeetCode --- 16. 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.
[code]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).
这道题的要求是在给定的正整数数组中,找到三个数,使其之和最接近给定的数字target,并返回这三个数字之和。可以假设每组输入有确切解。
这道题的思路和之前的Two Sum和3Sum差不多,简单方式是暴力查找,先排序,然后3层循环遍历数组,时间复杂度O(n3)。优化时,可以先固定一个数,再用两个指针l和r从这个数后面的两边往中间查找,逐个比较这三个数字之和与target的差距,记录最小的情况,当这三个数之和大于target的时候,r左移,而当之和小于target的时候,l右移,直到l和r相遇。这个其实就是在Two
Sum外层加1层循环,也和3Sum的复杂度一样,因此时间复杂度是排序的O(nlogn)加O(n2),即O(n2)。
时间复杂度:O(n2)
空间复杂度:O(1)
[code] 1 class Solution 2 { 3 public: 4 int threeSumClosest(vector<int> &num, int target) 5 { 6 sort(num.begin(), num.end()); 7 8 int closest = num[0] + num[1] + num[2]; 9 10 for(int i = 0; i < num.size() - 2; ++ i) 11 { 12 if(i > 0 && num[i] == num[i - 1]) // 跳过重复元素 13 continue; 14 15 int l = i + 1, r = num.size() - 1; 16 while(l < r) 17 { 18 if(abs(num[i] + num[l] + num[r] - target) < abs(closest - target)) 19 closest = num[i] + num[l] + num[r]; 20 21 if(num[l] + num[r] == target - num[i]) 22 return target; 23 else if(num[l] + num[r] > target - num[i]) 24 -- r; 25 else 26 ++ l; 27 } 28 } 29 30 return closest; 31 } 32 };
转载请说明出处:LeetCode --- 16. 3Sum Closest
相关文章推荐
- LeetCode-16-3Sum-Closest 贪心
- LeetCode16 3Sum Closest
- [LeetCode16]3Sum Closest
- LeetCode16 3Sum Closest
- LeetCode 16 - 3Sum Closest
- leetcode question 16: 3Sum Closest
- leetcode——16——3Sum Closest
- LeetCode - 16. 3Sum Closest
- leetcode--16. 3Sum Closest
- leetcode解题之 16. 3Sum Closest Java版(结果离目标值最近三个数字和)
- leetcode_16题——3Sum Closest(两个指针)
- leetcode 16 -- 3Sum Closest
- LeetCode 16: 3Sum Closest
- LeetCode 16_3Sum Closest
- [leetcode 15] 3sum && [leetcode 16] 3sum closest
- leetcode[16]3Sum Closest
- leetcode ----16. 3Sum Closest
- Leetcode 16 3Sum Closest
- LeetCode(16)3Sum Closest
- [LeetCode] 16. 3Sum Closest