Skip to content

Instantly share code, notes, and snippets.

@zhyd1997
Created August 16, 2022 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhyd1997/2ef651d8e0eeb55bb908be4dc3e7e01c to your computer and use it in GitHub Desktop.
Save zhyd1997/2ef651d8e0eeb55bb908be4dc3e7e01c to your computer and use it in GitHub Desktop.
`indexOf` vs `Map`
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