这是题目https://leetcode.com/problems/two-sum/
这是我的写法:
var twoSum = function(nums, target) {
var len = nums.length,
i = 0,
hash = {},
res = [],
t1, t2;
while (i < len) {
hash[nums[i]] = i + 1;
t1 = len - i - 1;
t2 = hash[target - nums[t1]];
if (t2 && t2 != t1 + 1) {
res.push(++t1);
t1 > t2 ? res.unshift(t2) : res.push(t2);
break;
}
hash[nums[t1]] = t1 + 1;
i++;
}
return res;
};
才在中间位置
通过了一般是思路没有问题
跑得慢多半是因为细节没有注意
c#的,beat 90%
public int[] TwoSum(int[] nums, int target)
{
var hasttable = new Hashtable();
for (var i = 0; i < nums.Length; i++)
{
int x = nums[i];
if (hasttable.ContainsKey(target - x))
{
return new int[] { (int)hasttable[target - x] + 1, i + 1 };
}
if (!hasttable.ContainsKey(x))
{
hasttable.Add(x, i);
}
}
return new int[] { 0, 0 };
}