LeetCode Two Sum
来源:互联网 发布:源码时代教育怎么样 编辑:程序博客网 时间:2024/05/24 03:02
Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { int i = 0, j = numbers.size() - 1; vector<int> num(numbers); vector<int> r; sort(num.begin(),num.end()); while(i < j) { if(num[i]+num[j] == target) break; else if(num[i]+num[j] < target) i++; else j--; } for(int k = 0; k < numbers.size(); k++) { if(numbers[k] == num[i] || numbers[k] == num[j]) r.push_back(k+1); } return r; }};思路:解法时间复杂度O(nlogn),首尾指针向中间逼近,直到遇到两数和为target,下面证明这种方法。
设num中,满足num[m] + num[n] = target。
(1).首先考虑算法开始时, i = m, j = n 的情况,显然算法正确。
(2).首先考虑算法开始时, i = m, j ≠ n 或 i ≠ m, j = n的情况,显然算法接下来将要执行的是:i 或 j 其中一个不动,另一个不断向中间移动,最后到达 i = m, j = n。
(3).然后考虑算法开始时,i ≠ m, j ≠ n 即 i < m, j > n 的情况。若 num[i]+num[j] < target ,因为数组是有序的,所以可以推出 num[i] + num[k] < target (i<k<=j),也就是说num[i]与所有其他数都无法成功加和到target,所以可以淘汰;num[i]+num[j] > target 同理。这一步之后的 i, j 虽然移动了,但实际上可以看成还是在一个数组的首尾两端, i 前面的元素或 j 后面的元素已经被淘汰。因此这一步可以看成又回到了算法的开始,情况为(1)或(2)或(3)。而因为正确答案肯定存在,所以最后必将回到(1)或(2)。因此,算法正确。
暴力解法时间复杂度O(n^2),因为超时无法通过。
附:暴力解法
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> r(2,0); for(int i = 0; i < numbers.size(); i++) { for(int j = i + 1; j < numbers.size(); j++) { if(numbers[i]+numbers[j]==target) { r[0] = i + 1; r[1] = j + 1; return r; } } } }};
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- javascript中undefined和null的区别
- ecplise中的快捷键
- 七种进程间通信方式
- 使用命令行界面删除SSD系统盘上的hiberfil.sysw文件
- nothing is impossible to a willing heart
- LeetCode Two Sum
- Linux显示用户的ID
- Same Tree
- POJ 2612/ZOJ 1862 Mine Sweeper
- UVA-11624 Fire!
- Linux显示目前与过去登入系统的用户相关信息
- SDJZU_新生_贪心_今年暑假不AC
- CSU 1355地雷清除计划 网格图清除最少的地雷使得对角联通 最小割
- Unix编程之size_t、ssize_t