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
- [leetcode]-twoSum
- [leetcode]twoSum
- LeetCode-TwoSum
- 【Leetcode】TwoSum
- LeetCode - TwoSum
- leetcode :twoSum
- leetcode TwoSum
- leetcode twosum
- leetcode--twoSum
- LeetCode twoSum
- LeetCode-TwoSum
- leetcode--twoSum
- leetcode TwoSum
- TwoSum leetcode
- leetcode:twosum
- leetcode:TwoSum
- LeetCode---TwoSum
- LeetCode-TwoSum
- Android listView的应用以及Activity跳转
- iOS学习--UIWebView
- Android-调用本地方法传递数组参数/NDK-JNI开发实例(五)
- 面试题24:二叉搜索树的后序遍历序列
- UICollectionView 集合视图
- leetcode:twosum
- 快速排序
- Objective-C之Mark
- Android:Layout_weight的深刻理解
- UVA 1149 Bin packing
- 设计模式系列--备忘录模式
- 1094. The Largest Generation (25)
- mongodb创建用户操作
- android 屏幕适配