[LeetCode] 3Sum Closest
来源:互联网 发布:华裔女神陈曦 av淘宝 编辑:程序博客网 时间:2024/06/08 11:59
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).
解题思路:
类似于3Sum。首先给数组排序,用两个变量分别记录当前最小距离和最近的和。代码如下,时间复杂度为O(n^2)
class Solution {public: int threeSumClosest(vector<int> &num, int target) { int len=num.size(); if(len<3){ return 0; } std::sort(num.begin(), num.end()); int closest=num[0]+num[1]+num[2]; int minDis = abs(closest-target); for(int i=0; i<len; i++){ int start=i+1, end=len-1; while(start<end){ int sum=num[i]+num[start]+num[end]; int dis=abs(sum-target); if(dis<minDis){ minDis=dis; closest=sum; } if(sum>target){ end--; }else{ start++; } } } return closest; } int abs(int a){ return a>=0?a:-a; }};
0 0
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- [LeetCode] 3Sum Closest
- 【leetcode】3Sum Closest
- [LeetCode]3Sum Closest
- LeetCode-3Sum Closest
- LeetCode:3Sum Closest
- LeetCode | 3Sum Closest
- 【leetcode】3Sum Closest
- Leetcode: 3Sum Closest
- 代码开发过程中对日志的使用总结
- iOS 应用中分析如何使用常用的几种数据存储方式
- activemq持久化配置,设置为主从模式(带复制的主从模式,应用mysql数据库)
- 如何在谷歌卫星地图中叠加等高线并打印
- 大型网站架构的演变
- [LeetCode] 3Sum Closest
- C++中的单例模式
- LeetCode Copy List with Random Pointer
- OC中集合与java中集合的比较(2)NSDictionary
- Posix多线程编程学习笔记(二)—线程属性(1)
- jQuery选择器
- Android开发环境
- (1.5.1.3)编程之美:一摞烙饼的排序
- 关于List的toString方法调用的是否是父类Object的,explise显示是的,但其实不是,是AbstractCollection的,他复写了Object的toString