LeetCode Two Sum Total
来源:互联网 发布:php 类 编辑:程序博客网 时间:2024/06/05 04:57
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
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
思路: 使用map来映射所对应的数,方便查找.
代码:
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target){map<int, int> M;bool flag = 0;int index1 = 0;vector<int> index(2,0);for(int i = 0; i != numbers.size(); i++){M[numbers[i]] = i + 1;}for(int i = 0; i != numbers.size(); i++){if(M.find(target - numbers[i]) != M.end()){index1 = M[target - numbers[i]];if(index1 == i + 1) continue;//如果是同一个元素不算答案else {index[0] = index1 > i + 1? i + 1 : index1;index[1] = index1 > i + 1? index1 : i + 1;flag = 1;break;}}}return index;}};
0 0
- LeetCode Two Sum Total
- 【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
- 工厂方法模式(Factory Method Pattern) 应用篇(上)
- 如果你看不懂KMP算法,那就看一看这篇文章( 绝对原创,绝对通俗易懂)
- setup for android
- struts2中重定向中文参数乱码梳理
- 厂方法模式(Factory Method Pattern) 应用篇(下)
- LeetCode Two Sum Total
- java集群
- 操作系统相关知识
- 并查集
- Flexbox响应式菜单
- VS2012静态链接设置
- 工厂方法模式和IoC/DI的关系
- Inferring Taxi Status Using GPS Trajectories论文思路
- Android开发:输入法键盘的显示和隐藏