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

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
原创粉丝点击