LeetCode[Hash Table]: Two Sum
来源:互联网 发布:xp系统禁止安装软件 编辑:程序博客网 时间:2024/05/22 05:17
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
Brute force
vector<int> twoSum(vector<int> &numbers, int target) { vector<int> answer; for (int i = 0; i < numbers.size() - 1; i++) for (int j = i + 1; j < numbers.size(); j++) if (numbers[i] + numbers[j] == target) { answer.push_back(i + 1); answer.push_back(j + 1); return answer; } return answer;}
Result: Time Limit Exceeded
Hash table
vector<int> twoSum(vector<int> &numbers, int target) { vector<int> answer; map<int, int> numMap; for (int i = 0; i < numbers.size(); i++) if (numMap.find(target - numbers[i]) != numMap.end()) { answer.push_back(numMap[target - numbers[i]] + 1); answer.push_back(i + 1); return answer; } else numMap[numbers[i]] = i; return answer;}
1 1
- LeetCode[Hash Table]: Two Sum
- leetcode Two Sum hash
- [leetcode][hash] Two Sum
- LeetCode--Two Sum(排序or Hash)
- Hash Table -- Leetcode problem454. 4Sum II
- 349. Intersection of Two Array leetcode (hash table)
- Hash Table -- Leetcode problem349. Intersection of Two Arrays
- Hash Table -- Leetcode problem350. Intersection of Two Arrays II
- leetcode: two sum, hash search solution, java. O(n)
- leetcode--Two Sum--无序关联容器--hash map
- 【Leetcode】Two Sum (Sum)
- LeetCode[Hash Table]: Anagrams
- LeetCode:Hash Table
- LeetCode Summary Hash Table
- LeetCode-Hash Table
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- 自来水净化设备:直饮净化水设备工作原理及安装事项
- C语言的malloc、calloc、realloc
- Andorid 屏幕适配
- 最速下降优化算法与共轭梯度算法
- 网络安全相关站点
- LeetCode[Hash Table]: Two Sum
- 开始使用Mac OS X——写给Mac新人
- android 事件传递机制
- 关于oracle读取数据时,自动进行HASH处理的隐含参数:_gby_hash_aggregation_enabled
- 第13周项目1 数据大折腾3
- java中的AES 256算法遇到 Illegal key size or default parameters错的解决办法
- nyoj 915 +-字符串(贪心)
- window 下 go lang 环境变量一键批处理设置
- Android Activity与Service间的通讯之一(回调函数)