๋ฌธ์ ๋งํฌ
Reduce Array Size to The Half - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
๋ฐฐ์ด์ด ์ฃผ์ด์ง๋ ํด๋น ๋ฐฐ์ด์ ์ ์ผํ ์์ ( [3,3,3,3,3,4,4,4,5,5] ==> [3, 4, 5] )๋ฅผ ๊ตฌํ๊ณ
์๋ณธ ๋ฐฐ์ด์์ ์ ์ผํ ์์์ ๊ฐ์ ์์๋ฅผ ์ ๊ฑฐํ ๊ฒฝ์ฐ
์ ๊ฑฐํ ๋ฐฐ์ด์ด ์๋ณธ ๋ฐฐ์ด์ ํฌ๊ธฐ์ ์ ๋ฐ๋ณด๋ค ์์์ง ๋ ์ ๊ฑฐํ ์ ์ผํ ์์์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค. (์ ์ผํ ์์๋ ์ต์๋ก ์ ๊ฑฐํด์ผํ๋ค.)
์ ๊ทผ ๋ฐฉ๋ฒ
์ฃผ์ด์ง ์๋ณธ ๋ฐฐ์ด์ ์์๋ฅผ ๊ฐ์ ์์๊ฐ ๋ง์ ์์๋ก ์ ๋ ฌํ๊ณ ๋ง์ ์์๋ถํฐ ์ง์ฐ๋ฉด ํด๊ฒฐ ๊ฐ๋ฅํ ๋ฏ ํ๋ค.
(ex => [5, 5, 3, 2, 6, 3, 3, 1, 3]์ [3, 3, 3, 3, 5, 5, 2, 1] ์์๋ก ์ ๋ ฌ)
ํ์ง๋ง ๋ฐฐ์ด์์ ์ด๋ฐ ๋ฐฉ์์ผ๋ก ์ ๋ ฌํ ๋ฐฉ๋ฒ์ด ์๋ค. (์์์ง๋ ๋ชจ๋ฅด์ง๋ง..)
๋๋ฌธ์ HashMap์ ์ฌ์ฉํ์ฌ value๊ฐ ๊ฐ์ฅ ํฐ ์์๋ก ์ ๋ ฌํ๋ ๋ฐฉํฅ์ผ๋ก ์งํํ์๋ค.
๋จผ์ Map ์๋ฃ๊ตฌ์กฐ๋ฅผ ๋ง๋ค๊ณ ๋ฐฐ์ด์ ์์๋ฅผ key, ์์์ ๊ฐ์๋ฅผ value๋ก ์ฑ์ด๋ค.
arr.forEach(e => { map.has(e) ? map.set(e, map.get(e) + 1) : map.set(e, 1); })โ
๊ทธ๋ฆฌ๊ณ map์ value๋ฅผ ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌํ ๋ฐฐ์ด์ ๊ตฌํ๋ค.
const sortedValues = [...map.values()].sort((a,b) => b - a);โ
๋ง์ง๋ง์ผ๋ก sum ๋ณ์๋ฅผ ์์ฑํ๊ณ values์ ์ฒซ ์์๋ถํฐ ๋ํ ๋ค,
๋ง์ฝ arr / 2๋ณด๋ค sum์ด ์ปค์ง๋ฉด ๋ฉ์ถ๋ ์กฐ๊ฑด์ ์ถ๊ฐํ๋ค.
for(let value of sortedValues){ sum += value; output++; if(sum >= baseSize / 2){ break; } }โ
๋ง์ฝ ์ด๋ ์ ๊ฑฐํ ์์์ ์์ ์ฐพ๊ณ ์ถ์ผ๋ฉด map.values๊ฐ ์๋๋ผ map.entries๋ก key์ value๋ฅผ ๋ชจ๋ ๊ตฌํ๊ณ
output์ key๋ฅผ pushํ๋ฉด ๋๋ค.
/**
* @param {number[]} arr
* @return {number}
*/
var minSetSize = function(arr) {
const baseSize = arr.length;
const map = new Map();
let output = 0;
let sum = 0;
arr.forEach(e => {
map.has(e) ? map.set(e, map.get(e) + 1) : map.set(e, 1);
})
const sortedValues = [...map.values()].sort((a,b) => b - a);
for(let value of sortedValues){
sum += value;
output++;
if(sum >= baseSize / 2){
break;
}
}
return output;
};
'์ฝ๋ฉํ ์คํธ > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] Numbers With Same Consecutive Differences (0) | 2022.09.03 |
---|---|
[LeetCode] Rotate Image (0) | 2022.08.30 |
[LeetCode] Unique Morse Code Words (0) | 2022.08.17 |
[LeetCode] Combination Sum IV (0) | 2022.08.05 |
[LeetCode] My Calendar I (0) | 2022.08.03 |