๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Coding Test/Algorithms

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ฐ€์žฅ ํฐ ์ˆ˜/Java - Lv.2

by The Future Engineer, Lucy 2024. 10. 10.
728x90
๋ฐ˜์‘ํ˜•

โ“๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/42746?language=java

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

SW๊ฐœ๋ฐœ์ž๋ฅผ ์œ„ํ•œ ํ‰๊ฐ€, ๊ต์œก, ์ฑ„์šฉ๊นŒ์ง€ Total Solution์„ ์ œ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์„ ์œ„ํ•œ ๋ฒ ์ด์Šค์บ ํ”„

programmers.co.kr

์„ฑ๋Šฅ ์š”์•ฝ

๋ฉ”๋ชจ๋ฆฌ: 388 MB, ์‹œ๊ฐ„: 2896.82 ms

๋ฌธ์ œ ์„ค๋ช…

0 ๋˜๋Š” ์–‘์˜ ์ •์ˆ˜๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ •์ˆ˜๋ฅผ ์ด์–ด ๋ถ™์—ฌ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ์•Œ์•„๋‚ด ์ฃผ์„ธ์š”.

์˜ˆ๋ฅผ ๋“ค์–ด, ์ฃผ์–ด์ง„ ์ •์ˆ˜๊ฐ€ [6, 10, 2]๋ผ๋ฉด [6102, 6210, 1062, 1026, 2610, 2106]๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๊ณ , ์ด์ค‘ ๊ฐ€์žฅ ํฐ ์ˆ˜๋Š” 6210์ž…๋‹ˆ๋‹ค.

0 ๋˜๋Š” ์–‘์˜ ์ •์ˆ˜๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด numbers๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ์ˆœ์„œ๋ฅผ ์žฌ๋ฐฐ์น˜ํ•˜์—ฌ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊พธ์–ด return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

์ œํ•œ ์‚ฌํ•ญ

  • numbers์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 100,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • numbers์˜ ์›์†Œ๋Š” 0 ์ด์ƒ 1,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • ์ •๋‹ต์ด ๋„ˆ๋ฌด ํด ์ˆ˜ ์žˆ์œผ๋‹ˆ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊พธ์–ด return ํ•ฉ๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ

numbers return
[6, 10, 2] "6210"
[3, 30, 34, 5, 9] "9534330"

โœ๐Ÿปํ’€์ด

์ •์ˆ˜๋ฅผ ๋ฌธ์ž๋กœ ๋ฐ”๊ฟ” ๋ฐฐ์—ด๋กœ ์ €์žฅ.
๊ฐ ๋ฌธ์ž์˜ ํ•ฉ์„ ๋น„๊ตํ•˜์—ฌ ๊ฐ€์žฅ ํฐ ์ˆ˜๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ž๋ฅผ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ.
answer์— ์ •๋ ฌ๋œ ๋ฌธ์ž๋ฅผ ๋ชจ๋‘ ๋”ํ•จ.
๋งŒ์•ฝ ๋ฌธ์ž์—ด์˜ ์•ž์ด 0์ด๋ผ๋ฉด ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ํฐ ์ˆ˜๋Š” 0์ด๋ฏ€๋กœ 0์„ ๋ฐ˜ํ™˜. ๊ทธ ์™ธ๋Š” answer๋ฅผ ๋ฐ˜ํ™˜.

๐Ÿ’ป์ฝ”๋“œ

import java.util.*;

class Solution {
    public String solution(int[] numbers) {
        String answer = "";

        List<String> snum = new ArrayList<>();
        for(int i : numbers)
            snum.add(String.valueOf(i));

        snum.sort((o1, o2) -> ((o2 + o1).compareTo(o1 + o2)));

        for(int i = 0; i < numbers.length; i++)
            answer += snum.get(i);

        return answer.charAt(0) == '0' ? "0" : answer;
    }
}
728x90
๋ฐ˜์‘ํ˜•