LeetCode --- 16. 3Sum Closest
来源:互联网 发布:道路弯沉值计算软件 编辑:程序博客网 时间:2024/05/01 09:37
题目链接: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.
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)
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 else26 ++ l;27 }28 }29 30 return closest;31 }32 };
转载请说明出处:LeetCode --- 16. 3Sum Closest
0 0
- LeetCode 16. 3Sum Closest
- LeetCode --- 16. 3Sum Closest
- [Leetcode] 16. 3Sum Closest
- 【leetcode】16. 3Sum Closest
- [leetcode] 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- LeetCode - 16. 3Sum Closest
- [LeetCode]16. 3Sum Closest
- LeetCode 16. 3Sum Closest
- LeetCode *** 16. 3Sum Closest
- Leetcode 16. 3Sum Closest
- leetcode 16. 3Sum Closest
- 【LeetCode】16. 3Sum Closest
- leetcode 16. 3Sum Closest
- 【leetcode】16. 3Sum Closest
- leetcode 16. 3Sum Closest
- zoj 3213 Beautiful Meadow(插头dp)
- 最短路径
- 欢迎使用CSDN-markdown编辑器
- poj 1018 dp\枚举+剪枝 (选择带宽)
- 浅谈Java程序加载机制
- LeetCode --- 16. 3Sum Closest
- (hdu step 2.1.5)七夕节(球一个数的所有因子之和)
- asd
- LeetCode --- 17. Letter Combinations of a Phone Number
- ActiveMQ 即时通讯服务 浅析
- TCP/IP协议和OSI参考模型
- 获取wifi热点配置信息
- LeetCode --- 18. 4Sum
- Comparison between the simplex algorithm and interior point method