字典
- 与集合类似也是一种存储唯一的数据结构,但它以键值对的形式存储
- Es6 有字典名为map
求交集
let m = new Map();let nums1 = [1,2,3,2];let nums2 = [2,4,5,8,9,2,1];let res = [];nums1.forEach(num => {m.set(num,true)});nums2.forEach(num => {if(m.get(num)){res.push(num);m.delete(num)}})console.log(res)
有效括号算法优化
const arr1 = [1,1,2,2];const set = new Set(arr1);const set2 = new Set([2,3]);const theSame = [...set].filter((item)=>{set2.has(item)})const deferent = [...set].filter((item)=>{!set2.has(item)})console.log('theSam1');console.log(theSame);console.log('deferent');console.log(deferent)
两数之和算法优化
给定 nums = [2,7,11,15] target = 9,因为nums[0] + nums[1] = 9,所以返回[0,1]
let nums = [10,2,15,26];let target = 25;let numsAdd = function(numArray,target){let map = new Map();for(let i = 0;i<numArray.length;i++){let n = numArray[i];let n2 =target - n;if(map.has(n2)){return [map.get(n2),i]}else{map.set(n,i)}}};console.log(numsAdd(nums,target))
无重复字符的最长子串(使用左右指针形成滑动窗口)
let strings = ['a','c','b','a','d','e'];let getSubstringLength = function(string){let leftIndex = 0;let res = 0; //子字符串的长度let map = new Map();for(let rightIndex = 0;rightIndex<string.length;rightIndex++){if(map.has(string[rightIndex])){leftIndex = map.get(string[rightIndex])+1};res = Math.max(res,rightIndex - leftIndex + 1);map.set(string[rightIndex],rightIndex);}return res}console.log(getSubstringLength(strings));
