Created
August 16, 2022 02:07
-
-
Save zhyd1997/2ef651d8e0eeb55bb908be4dc3e7e01c to your computer and use it in GitHub Desktop.
`indexOf` vs `Map`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function firstUniqCharWithHashMap(str) { | |
const map = new Map(); | |
for (let i = 0; i < str.length; i++) { | |
const char = str.charAt(i); | |
if (!map.has(char)) { | |
map.set(char, [i, 1]); | |
} else { | |
map.set(char, [i, map.get(char) + 1]); | |
} | |
} | |
for (let entry of map.values()) { | |
if (entry[1] == 1) { | |
return entry[0]; | |
} | |
} | |
return -1; | |
} | |
function firstUniqCharWithIndexOf(str) { | |
const arr = str.split(""); | |
for (let i = 0; i < arr.length; i++) { | |
const idx = arr.indexOf(arr[i]); | |
const lastIdx = arr.lastIndexOf(arr[i]); | |
if (idx === lastIdx) { | |
return i; | |
} | |
} | |
return -1; | |
} | |
const t0 = performance.now(); | |
for (let i = 0; i < 1000000; i++) { | |
firstUniqCharWithHashMap("loveleetcode"); | |
} | |
const t1 = performance.now(); | |
const t2 = performance.now(); | |
for (let i = 0; i < 1000000; i++) { | |
firstUniqCharWithIndexOf("loveleetcode"); | |
} | |
const t3 = performance.now(); | |
console.log('HashMap: ' + (t1 - t0) + 'ms'); | |
console.log('IndexOf: ' + (t3 - t2) + 'ms'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment