【LeetCode】1. Two Sum
2015-12-30 18:01
369 查看
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,用c++11中的hash表unordered_map
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,用c++11中的hash表unordered_map
[code]#include<iostream> #include <stack> #include <queue> #include <unordered_map> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; unordered_map<int, int> hash_map; for (int i = 0; i < nums.size(); i++){ hash_map[nums[i]] = i; } int other = 0; for (int i = 0; i < nums.size(); i++){ other = target - nums[i]; if (hash_map.find(other) != hash_map.end()){ if (i == hash_map[other]) continue; else if(i < hash_map[other]){ result.push_back(i + 1); result.push_back(hash_map[other] + 1); return result; } else{ result.push_back(hash_map[other] + 1); result.push_back(i + 1); return result; } } } } }; int main() { int numbers[] = { 2, 7, 11, 15 }, target = 9; vector<int> nums; nums.push_back(2); nums.push_back(7); nums.push_back(11); nums.push_back(15); Solution s; nums = s.twoSum(nums, 9); for (int i = 0; i < nums.size(); i++){ cout << nums[i] << " "; } return 0; }
相关文章推荐
- Eclipse中使用Gradle实现APK分包
- 开始学习Unity
- 如何计算oracle数据库内存
- MySQL主从复制
- Android之JAVASe基础篇-面向对象-多线程(七)
- Android Studio你不知道的调试技巧
- jQuery动态实现下拉菜单
- content delivery network
- 15个顶级Java多线程面试题及回答
- jQuery动态实现下拉菜单
- 博客搬家了,搬家了
- URL编码
- android自定义style
- OpenCV中mat的type
- Android混淆
- 完美解决!隐藏listview的headerView,实现动态下拉,(仿ios)
- ig.Entity.inject 植入属性
- layer-list(图层叠加)
- 关于 KVO 和 KVC 的一些总结 以及使用KVC进行字典和模型的互相转换
- 文章标题:HDU 2717 Catch That Cow