标签:
自己的C#代码(第一次接触哈希表,运行很费时,还没有被accept,先放这等着回去研究):
public class Solution {
public int[] TwoSum(int[] nums, int target) {
int index2 = 0;
int[] RetIndecis = {0,0};
Hashtable hsNums = new Hashtable();
hsNums.Clear();
//i is the first index
for(int i=0;i<nums.Length;i++)
{
int j=i+1;
int targetValue = target - nums[i];
//if targetKey exist
if(hsNums.ContainsValue(targetValue))
{
foreach (DictionaryEntry deNum in hsNums)
if (deNum.Value.Equals(targetValue) && !deNum.Key.Equals(j))
{
index2 = (int)deNum.Key;
RetIndecis[1] = j;
RetIndecis[0] = index2;
return RetIndecis;
}
}
hsNums.Add(i + 1,nums[i]);
}
return(RetIndecis);
}
}
别人的C++代码:(via naveed.zafar https://leetcode.com/discuss/10947/accepted-c-o-n-solution)
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
//Key is the number and value is its index in the vector.
unordered_map<int, int> hash;
vector<int> result;
for (int i = 0; i < numbers.size(); i++) {
int numberToFind = target - numbers[i];
//if numberToFind is found in map, return them
if (hash.find(numberToFind) != hash.end()) {
//+1 because indices are NOT zero based
result.push_back(hash[numberToFind] + 1);
result.push_back(i + 1);
return result;
}
//number was not found. Put it in the map.
hash[numbers[i]] = i;
}
return result;
}
};
标签:
原文地址:http://www.cnblogs.com/xquancnblogs/p/5082502.html