Two Sum
来源:互联网 发布:删除文件 linux 编辑:程序博客网 时间:2024/04/29 10:20
原题链接:http://oj.leetcode.com/problems/two-sum/
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
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { }};
解决思路:
1.最简单,进行2重遍历,对任意一对数字进行相加看是否满足target值,若满足返回下标。运行时间为N*N,太慢。
2.假设这一串数字中V1+V2=TARGET,且V1在V2之前,则我们可以想象,如果我们没遇到一个数,就保存期与target的差值,则在遇到一个前面已存在的差值相等的新数字,则满足。如在遇到V1时保存TARGET-V1的值为V2,在真正遇到V2时,我们发现正是需要的。
采用map<int ,int>,key为每次计算的差值,value为其下标。
新来一个数字,查看是否map中存在与其相等的值,若存在,则满足。若不存在,计算与target差值,并保存在map中。
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { map<int, int> value_index; for(vector<int>::size_type i = 0; i<numbers.size(); i++){ int number = numbers[i]; map<int, int>::iterator it = value_index.find(number); if(it==value_index.end()){ value_index.insert(map<int, int>::value_type(target-number, i+1)); } else{ int index1 = i+1; int index2 = it->second;numbers.clear();numbers.push_back(index2);numbers.push_back(index1);return numbers; } } }};
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- EIP寄存器
- 编程序将一个字符串的前N个子字符送到一个字符型数组中去,然后再加上一个'\0'(不允许使用strcoy(str1,str2,n)函数)。
- Android 新API 之 MediaCodec使用笔记
- Bundle savedInstanceState的作用
- hash table相关--引入哈希桶的概念来实现一个哈希表
- Two Sum
- Cows - POJ 2481 树状数组
- Linux下指定动态库的加载路径
- IIS管理器里添加虚拟目录,提示: “/”应用程序中的服务器错误。用户 'NT AUTHORITY\IUSR' 登录失败
- 搜寻马航MH370有多烧钱?澳方花费惊人
- 一位女上司写给自己女下属的信
- Nginx内核参数相关的优化设定
- WP8 Pivot 控制某一页的左右滑动或锁定某一页
- Acceptor类介绍[4-0]