Leetcode(一)JS实现hash表
Question:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Solution:
-
暴力搜索方式
var twoSum = function(nums, target) { var result = []; for(var i = 0,len = nums.length;i < len;i++){ for(var j = i+1,item2;j < len;j++){ if(nums[i] + nums[j] == target){ result.push(i); result.push(j); return result; } } } };
这种方式下:
-
- 时间复杂度:每次循环都将数组的剩余元素进行遍历,该操作的时间复杂度为O(n),因此总时间复杂度为O(n^2)
- 空间复杂度:O(1)
- hash表
hash表是一种典型的利用键值对存储并检索数据的非线性结构,使用键值对进行数据的存储,在数据的存储位置和它的关键字之间建立了一一对应的关系,从而使每个关键字和结构中的一个唯一的存储位置相对应。
JS并不提供hash表结构,因此需要使用对象概念模拟hash表,再利用原生hasOwnProperty方法即可实现:
function Hashtable(){ this._hash = {}; this._count = 0; this.add = function(key, value) {//当关键字存在,则将此关键字对应的旧对象更新为新的对象Value this._hash[key] = value; if (!this.containsKey(key)) this._count++; } this.containsKey = function(key) { return this._hash.hasOwnProperty(key); } this.remove = function(key) { if(this.containsKey(key)){ delete this._hash[key]; this._count--; } } this.count = function() { return this._count; } this.getValue = function(key) { if (this.containsKey(key)) { return this._hash[key]; } } this.clear = function() { this._hash = {}; this._count = 0; } } function twoSum(arr,target){ var ht = new Hashtable(); var result = []; for(var i =0 ,len = arr.length ; i<len ; i++){ ht.add(arr[i],i) } for(var i =0 ,len = arr.length ; i<len ; i++){ var complement = target - arr[i]; if( ht.containsKey(complement) && ht.getValue(complement) !== i){ result.push(i); result.push(ht.getValue(complement)); return result; } } throw Error("No two sum solution") } console.log(twoSum([0,1,2,0,3],0))