javascript -- leetcode two sum , 这个题还有更优的解法吗?

这是题目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;
};

才在中间位置
图片描述

阅读 6.2k
3 个回答
新手上路,请多包涵

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 };
}

通过了一般是思路没有问题
跑得慢多半是因为细节没有注意

这个大约击败了91.54%

var twoSum = function(nums, target) {
    let arr = [],
        hash = {},
        len = nums.length,
        t1, index = 0, t2;
    while (index < len) {
        t2 = len - index - 1;
        hash[nums[t2]] = t2;
        t1 = hash[target - nums[index]];
        if (t1 !== undefined && t1 !== index) {
            arr.push(index)
            index > t1 ? arr.unshift(t1) : arr.push(t1);
            break;
        }
        hash[nums[index]] = index;
        index++;
    }
    return arr;
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题