leetcode Two Sum 哈希表
2015-07-06 19:12
337 查看
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
Hide Tags
Array Hash
Table
刚开始直接两层for循环超时,哈哈,还是要用哈希表。
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
Hide Tags
Array Hash
Table
刚开始直接两层for循环超时,哈哈,还是要用哈希表。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int>res; if (!nums.size()) return res; map<int, int>Hash; for (int i = 0; i < nums.size(); i++) { if (Hash.find(target - nums[i]) != Hash.end()) { res.push_back(Hash[target - nums[i]]+1); res.push_back(i+1); return res; } Hash[nums[i]] = i; } return res; } };
相关文章推荐
- Cannot run program "XXXXX/android-sdks/build-tools/aapt.exe": error=2,
- JavaWeb知识点总结一
- 关于MSDK的几个难点
- 86.求出分数前n项和
- [转]短信验证码如何防止不恶意点击被刷!
- MongoDB: The Definitive Guide
- 梯度下降
- 输入一行字符,统计有多少个单词
- 猴子向右看,FOJ上某题 单调栈
- 应对黑客攻击SQL SERVER数据库中的一个案例
- linux常用查看硬件设备信息命令
- Actionbar Demo
- Binary Tree Right Side View
- 树状数组入门
- MonkeyRunner源代码分析Android通信设备
- 初学_Android4高级编程-4 简单的Adapter
- 求两个字符串的最长公共子串
- block传值的简单使用
- Pizza pieces
- 初学_Android4高级编程-3 自定义View