码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode -1 two sum

时间:2015-12-28 15:41:57      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

 

自己的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;
}
};

 

LeetCode -1 two sum

标签:

原文地址:http://www.cnblogs.com/xquancnblogs/p/5082502.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!