题目:给定一个整型数组,找到两个相加等于特定值的数的index(从1开始,第一个下标值应小于第二个)。
先写了一个最普通的想法,从前往后撸,跟冒泡似的。果然,超时了。
没有思路,看解析说 哈希。果断关掉解析。查找数据结构的哈希表,哈希查找。调试多时,通过。
Ugly代码如下:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
//int harfTarget=target/2;
vector<int> answer(2);
int key;
bool hasFound=false;
vector<int>::iterator end = numbers.end();
vector<int>::iterator start = numbers.begin();
int addition = end-start;
vector<int> hashTable(3*addition,0);
int hashindex;
for(vector<int>::iterator it = numbers.begin();it != numbers.end();it++)
{
key=*it;
hashindex = hash(key,addition);
while(hashTable[hashindex]!=0)
{
hashindex = hashindex + addition+1;
}
hashTable[hashindex]=it-start+1;
}
for(vector<int>::iterator it = numbers.begin() ;it !=numbers.end()&&!hasFound ; it++)
{
int i = it-start;
//if(numbers[i]<=harfTarget)
//{
answer[0]=i+1;
hashindex = hash(target-*it,addition);
while(hashTable[hashindex]!=0)
{
if(hashTable[hashindex]>answer[0]&&numbers[hashTable[hashindex]-1]==(target-*it))
{
answer[1]=hashTable[hashindex];
hasFound=true;
break;
}
else
{
hashindex=hashindex+addition+1;
}
}
//}
}
return answer;
}
int hash(int key,int mod)
{
return (key%mod)+1;
}
};
反思:
1,数据结构和算法放手了太久,穷举方法不能过的时候,竟然没有什么思路。知道看见哈希两个字,才恢复过来。
2,C++需要上手。本科用C,上研后用matlab,对标准库太不了解,导致代码又长又丑。
3,读题不仔细,以为输出要求是前面index所指向的数值要比后面的小,还计算了target/2来进行自以为是的优化。
解决方案:
结合leetCode, 进行C++STL的掌握和算法数据结构的回顾。
阅读Programming principles and practice using C++ 、Accelerated C++
阅读Algorithms配合LeetCode。