<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>
时间: 2024-10-08 02:45:21