LeetCode 01 Two Sum
来源:互联网 发布:小企业财务会计软件 编辑:程序博客网 时间:2024/04/30 14:45
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
此题乍一看很简单,只要遍历数组,需找target-numbers[i]的元素即可,算法复杂度为O(n*n),但这样是会超时,不被接受。该方法需要多次扫描数组,而每次扫描的信息又没有被记住,造成信息的浪费。
最好的方法是能够扫描一次,但能够记住每个元素的位置。因此可以使用C++的map类。
第一次扫描,将每个元素及其坐标加入到map中。
第二次扫描,在map中查找target-numbers[i]的元素,要注意target = 2*numbers[i]的情形。map底层是基于红-黑树的,查找复杂度可以认为是O(1)。
这样整个算法的时间复杂度可以认为是O(n).
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> out; map<int, int> hash_map; int tmp ; int index; size_t length = numbers.size(); for (int i =0; i<length; i++) { //if (!hash_map.count(numbers[i])) { hash_map.insert(pair<int, int>(numbers[i], i)); //} } for (int i =0; i<length; i++) { tmp = target - numbers[i]; if (hash_map.count(tmp)) { index = hash_map[tmp]; if(index != i) { out.push_back(index+1); out.push_back(i+1); return out; } } } return out; }};
- LeetCode 01 Two Sum
- LeetCode 01 Two Sum
- Leetcode 01 Two Sum
- LeetCode:01:Two Sum
- LeetCode OJ 01 Two Sum
- 【Leetcode】Two Sum (Sum)
- LeetCode——01 Two Sum
- LeetCode刷题笔记 01 Two 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
- vnc的启动与停止glassfish在linux下命令行启动与停止
- JSP C标签 示例 待续
- Android底层开发之红外遥控驱动移植
- 关于el表达式,ognl表达式,JSTL的区别
- 字符数组查找-----拉手笔试
- LeetCode 01 Two Sum
- 性能问题,如何定位一个应用响应慢等性能问题
- 黑马程序员——面向对象程序设计
- [Leetcode]Flatten Binary Tree to Linked List (三种方法)
- 如何实现servlet的线程安全
- 华为荣耀3C最新版ROM的root,(4.7.1和4.8.1等等通用方法)
- servlet是只有一个实例吗
- Permutation I,II
- opencv中遍历图像(IplImage格式)