javascript -- leetcode two sum , 这个题还有更优的解法吗?
ringa_lee
ringa_lee 2017-04-10 15:22:37
[JavaScript讨论组]

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

才在中间位置

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
黄舟

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 };
}
大家讲道理

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号