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
1、这种题放在第一,这要是当初一上来就做这个肯定做不出来。不过,到现在第一道做的Zigzag还没找出错误来。
2、<int>vector num(2)类似这种初始化,num中会存在两个数据0。
3、multimap一个键对应多个值的输出,原文地址:点击打开链接
在multimap中,同一个键关联的元素必然相邻存放。基于这个事实,就可以将某个键对应的值一一输出。
1、使用find和count函数。count函数求出某个键出现的次数,find函数返回一个迭代器,指向第一个拥有正在查找的键的实例。
2、使用lower_bound(key)和upper_bound(key)
lower_bound(key)返回一个迭代器,指向键不小于k的第一个元素
upper_bound(key)返回一个迭代器,指向键不大于k的第一个元素
3、使用equat_range(key)
返回一个迭代器的pair对象,first成员等价于lower_bound(key),second成员等价于upper_bound(key)
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
multimap<string,int> m_map;
string s("中国"),s1("美国");
m_map.insert(make_pair(s,50));
m_map.insert(make_pair(s,55));
m_map.insert(make_pair(s,60));
m_map.insert(make_pair(s1,30));
m_map.insert(make_pair(s1,20));
m_map.insert(make_pair(s1,10));
//方式1
int k;
multimap<string,int>::iterator m;
m = m_map.find(s);
for(k = 0;k != m_map.count(s);k++,m++)
cout<<m->first<<"--"<<m->second<<endl;
//方式2
multimap<string,int>::iterator beg,end;
beg = m_map.lower_bound(s1);
end = m_map.upper_bound(s1);
for(m = beg;m != end;m++)
cout<<m->first<<"--"<<m->second<<endl;
//方式3
beg = m_map.equal_range(s).first;
end = m_map.equal_range(s).second;
for(m = beg;m != end;m++)
cout<<m->first<<"--"<<m->second<<endl;
return 0;
}
下面是我的代码:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
multimap<int,int> index;
multimap<int,int>::iterator itr;
int i,j,count,len=numbers.size();
for(i=0;i<len;i++)
{
index.insert(make_pair(numbers[i],i));
}
multimap<int,int>::iterator end=index.end();
for(i=0;i<len;i++)
{
j=target-numbers[i];
itr=index.find(j);
count=index.count(j);
if(itr!=end&&itr->second!=i)
{
int ii,jj;
if(count==2)
{
ii=itr->second;
++itr;
jj=itr->second;
}
else
{
ii=i<itr->second?i:itr->second;
jj=i>itr->second?j:itr->second;
}
++ii;++jj;
vector<int> two;
two.push_back(ii);
two.push_back(jj);
return two;
}
}
}
};