码迷,mamicode.com
首页 > Web开发 > 详细

[JS做LeetCode] Two Sum

时间:2015-03-21 18:18:53      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

Two Sum

<html>

<head>
    <meta http-equiv="charset" content="utf-8"></head>

<body>
    <script>
        var numbers=[2, 7, 11, 15];
        var target = 9;

        var twoSum = function(numbers, target) {
                // 用对象来模拟hash table
                // 将所有数组放进hash里面,key为当前值,value为下标
                var hash = {};
                for(var i=0; i<numbers.length; i++) {
                        hash[numbers[i]] = i;
                }

                // 遍历数组,如果hash里面有key和数组当前的值相加为target,那么就是那两下标了
                // 注意要判断两下标不能一样
                for(var i=0; i<numbers.length; i++) {
                        var needValue = target-numbers[i];
                        if(hash.hasOwnProperty(needValue)) {
                                var index1 = i+1;
                                var index2 = hash[needValue]+1;
                                if(index1!==index2) {
                                        return [index1, index2];
                                }
                        }
                }
        };

        alert(twoSum(numbers, target));
    </script></body>

 
 
 
 

[JS做LeetCode] Two Sum

标签:

原文地址:http://www.cnblogs.com/oadaM92/p/4355847.html

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