leetcode:twosum

来源:互联网 发布:网络运维工程师笔试题 编辑:程序博客网 时间:2024/05/16 12:44

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库和find函数

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> output;int len;len = nums.size();map<int, int> temp;for (int i = 0;i < len;i++){temp.insert(pair<int, int>(nums[i],i + 1));}map<int, int>::iterator itr;map<int, int>::iterator itp;for (itr = temp.begin();itr != temp.end();itr++){itp = temp.find(target - itr->first);if (itp != temp.end()){output.push_back(itr->second);output.push_back(itp->second);break;}}return output;    }};



这个程序验证基本是对的,但是有如下错误:

Input:[0,4,3,0], 0

Output:[1,1]

Expected:[1,4]

在本地验证是[1,1]对的,但是在leetcode的服务器上却显示错误

0 0