mirror of
https://github.com/prdlk/leetcode.git
synced 2026-08-02 17:31:40 +00:00
Leetcode 1365
function reduceArray(nums) {
const sorted = [...nums].sort((a, b) => a - b)
return nums.map((x) => {
nums.indexOf(sorted[x])
})
}
Creating a Frequancy Map
function reduceArray(nums) {
const freqMap = new Map()
nums.forEach((x) => {
if (freqMap.has(x)) {
freqMap.set(x, freqMap.get(x) + 1)
} else {
freqMap.set(x, 1)
}
})
return Array.from(freqMap.entries()).map(([k, v]) => v)
}
Hammer Tool
function hammer(arrOrStr) {
const freq = {};
for (let item of arrOrStr) {
freq[item] = (freq[item] || 0) + 1;
}
// Then either:
// A. Return freq map
// B. Sort using freq
return arrOrStr.slice().sort((a, b) => {
if (freq[b] !== freq[a]) return freq[b] - freq[a]; // desc freq
return a < b ? -1 : 1; // tiebreaker
});
}