Notice
Recent Posts
Recent Comments
Link
ยซ   2025/01   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Lennon FE

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.2] ํŠœํ”Œ (js) ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.2] ํŠœํ”Œ (js)

Lennon 2021. 11. 18. 14:42
728x90
๋ฐ˜์‘ํ˜•

https://programmers.co.kr/learn/courses/30/lessons/64065?language=javascript 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ํŠœํ”Œ

"{{2},{2,1},{2,1,3},{2,1,3,4}}" [2, 1, 3, 4] "{{1,2,3},{2,1},{1,2,4,3},{2}}" [2, 1, 3, 4] "{{4,2,3},{3},{2,3,4,1},{2,3}}" [3, 2, 4, 1]

programmers.co.kr

 

function solution(s) {
    let arr = [];
    let result = s.replace(/{/gi, "").replace(/}/gi,"").split(",").map((value) => {
        arr.push(parseInt(value));
    });
    
    arr.sort((a,b) => a - b);
    
    let count = 1;
    let obj = []; 
    for(let i = 0; i < arr.length; i++){
        if(arr[i] === arr[i+1]){
            count++;
        }
        else {
            obj.push({value : arr[i], count1 : count});
            count = 1;
        }
    }
    
    obj.sort((a,b) => b.count1 - a.count1);
    
    return obj.map((value, index) => {
        return value.value;
    })
}

 

s๊ฐ€ set๋ชจ์–‘ ๋ฌธ์ž์—ด๋กœ ์ฃผ์–ด์กŒ๊ธฐ ๋•Œ๋ฌธ์— arr์— ๊ฐ ๋ฌธ์ž๋ฅผ pushํ•œ๋‹ค.

 

ex) s = '{{1,2},{1,2,3,4}}' => arr = [1,1,2,2,3,4] ํ˜•์‹

 

๋‹ค์Œ arr์„ ์ •๋ ฌํ•˜๊ณ  obj์— ๋‚˜์˜จ ๋ฌธ์ž ๋ฐ count๋ฅผ ๊ฐ์ฒดํ˜•์‹์œผ๋กœ pushํ•œ๋‹ค.

 

ex) arr = [1,1,2,2,3,4]  => obj = [{value: 1, count: 2}, {value: 2, count: 2}, {value: 3, count: 1}, {value: 4, count: 1}]

 

๋‹ค์Œ count๊ฐ€ ๋‚ฎ์€ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ํ›„ ๋ฐฐ์—ดํ˜•์‹์œผ๋กœ ๋ฆฌํ„ดํ•˜๋ฉด ๋!

 

 

 

 

 

 

728x90
๋ฐ˜์‘ํ˜•
Comments