leetcode Two Sum
来源:互联网 发布:淘宝返利的网站有哪些 编辑:程序博客网 时间:2024/05/01 22:38
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
思路用multimap来存储numbers与下标,在查找的时候分两种情况,根据target == 2 * numbers[i]判断,如果是,需要找出第一个位置,并判断后一个位置的值是否等于numbers[i],第二种直接查找target-numbers[i],然后做判断即可。
vector<int> twoSum(vector<int> &numbers, int target) { multimap<int, int> maps; multimap<int, int>::iterator it; vector<int> vec; bool check; for(int i = 0; i < numbers.size(); i++){ check = false; maps.insert(make_pair(numbers[i], i)); it = maps.lower_bound(target - numbers[i]); if(target == 2 * numbers[i]){ it++; check = true; } if(it != maps.end() && it -> first == target - numbers[i]){ if(check) it--; vec.push_back(it->second +1); vec.push_back(i+1); break; } } return vec; }
0 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- Android判断服务器是否开启
- POJ 1001 大数
- JSONObject has no read method. SKIPPED
- Python 实现 淘宝秒杀 聚划算 自动提醒 源码
- C语言位字段应用
- leetcode Two Sum
- webservice锦集
- E0F
- [LeetCode] Search Insert Position
- 磁盘raid
- 用OpenSceneGraph实现的NeHe OpenGL教程 - 第二十七课
- 画图解释SQL联合语句
- c 语言语法
- 微信公众帐号开发教程第2篇-微信公众帐号的类型(普通和会议)