LeetCode 1 Two Sum
2016-02-11 17:22
579 查看
原创:/article/3656281.html
Question:
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
Question:
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
[code]class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int,int> mapping; vector<int> result; for(int i = 0; i < nums.size(); i++) { mapping[nums[i]] = i; } for(int i = 0; i < nums.size(); i++) { int searched = target - nums[i]; if(mapping.find(searched) != mapping.end() && mapping.at(searched) != i) { result.push_back(i + 1); result.push_back(mapping[searched] + 1); break; } } return result; } };
相关文章推荐
- Intent 传值和 Bundle传值的区别
- python3获取天气预报(转)
- Light OJ 1119 Pimp My Ride (简单状压DP)
- poj2955区间dp?
- c语言中结构,动态分配内存的理解
- Java—进程间通讯的有几种方法
- 2016蓝桥杯算法训练——大小写转换
- smartupload文件上传技术
- [剑指offer-1517]链表中倒数第k个结点
- Hdu 2041 超级楼梯 简单DP
- The Java™ Tutorials — Concurrency :Synchronization 同步
- 什么是Modernizr?
- Druid是什么和用StatViewServlet用于展示Druid的统计信息
- 接口举例
- mesos+marathon管理docker集群
- nyoj791color the fence
- 第十一章编程练习(5)
- Hdu 2044 一只小蜜蜂 简单DP
- Java theory and practice: More flexible, scalable locking in JDK 5.0
- HTML5开发实战——Sencha Touch篇(1)