LeetCode-Two sum
2015-06-09 20:18
381 查看
Question:
Give 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
Solution:
Give 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
Solution:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int,int> temp; vector<int> result; map<int,int>::iterator iter; int k; for(int i=0;i<nums.size();i++) { temp[nums[i]]=i+1; } for(int j=0;j<nums.size();j++) { int x=target-nums[j]; iter=temp.find(x); if(iter!=temp.end() && iter->second!=j+1) { k=iter->second; result.push_back(min(j+1,k)); result.push_back(max(j+1,k)); break; } } return result; } };
相关文章推荐
- Result Maps collection already contains value for
- 安装rlwrap for linux
- 使用.net和jquery实现一对一的网页聊天系统
- 一起学CUDA(一)
- 集合框架3+System+Runtime+Date+Math
- 一起学CUDA(零)
- 二次函数积分面积【数学】
- 第5题
- 最大子序列、最长递增子序列、最长公共子串、最长公共子序列、字符串编辑距离
- Linux 内核调试之 printk
- 优先队列(堆)的实现
- was--创建概要文件(典型)
- 最近在做的事以及一些安排
- netstat 的10个基本用法
- vs2010 将某一个类添加到一个名字空间中 vs2010创建名字空间及其使用
- mac基本使用技巧
- [JQ权威指南]第一天:事件操作链接式书写
- [BI项目记]-新任务创建
- 应聘互联网公司的简历应该是怎么样的?
- hdu3123GCC