Leetcode : Two Sum
来源:互联网 发布:php关联添加元素 编辑:程序博客网 时间:2024/04/27 16:43
Two SumMar 14 '11
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
思路:
1)从头到尾两两相加,很容易解决这个问题,但是需要时间复杂度O(n*n);
2)那有没有更快捷的方法呢,因为我们知道其中一个值A,只需要知道存不存在另外一个值B,使得A+B == target,所以用hash就能很好的解决这个问题
代码如下:
思路1:
class Solution{public: vector<int> twoSum(vector<int> &numbers, int target) { for (int i = 0; i < numbers.size() - 1; ++i) { for (int j = i + 1; j < numbers.size(); ++j) { if (numbers[i] + numbers[j] == target) { vector<int> index; index.push_back(i+1); index.push_back(j+1); return index; } } } }};
思路2:
class Solution{public: vector<int> twoSum(vector<int> &numbers, int target) { unordered_map<int,int> nums; for (size_t i = 1; i < numbers.size(); ++i) nums[numbers[i]] = i+1; for (size_t i = 0; i < numbers.size() - 1; ++i) { unordered_map<int,int>::iterator it = nums.find(target - numbers[i]); if (it != nums.end()) { vector<int> index; index.push_back(i+1); index.push_back(it->second); return index; } } }};
- 【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
- 黑马程序员_基础加强(7) 动态代理与AOP切面
- 关于org.hibernate.HibernateException: Error applying BeanValidation relational constraints的解决
- iOS开发之Object-C和Cocoa
- iOS中客户端与服务器连接相关
- iOS开发总结帖(Xcode、Object-C和Cocoa...更新中)
- Leetcode : Two Sum
- Javascript JQuery 图片预加载load事件IE不兼容的问题的解决方法
- 双向循环链表程序(C语言版)
- ComboBox 智能过滤,模糊匹配,拼音首字母匹配
- OpenMP编程指南
- WindowS下Ant的安装与配置
- 第四章Oracle恢复内部原理(热备份)
- DOS命令下使用sqlite3 命令中文乱码的解决办法
- 一次简单的POST注入测试