[programmers] ๊ฐ€์žฅ ํฐ ์ˆ˜ - Java

์ฃผ์–ด์ง„ ์ •์ˆ˜ ๋ฐฐ์—ด์—์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด, ์ •์ˆ˜๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•˜๊ณ , ํŠน์ • ๋น„๊ต ๊ธฐ์ค€์— ๋”ฐ๋ผ ์ •๋ ฌํ•œ ํ›„, ์ •๋ ฌ๋œ ๋ฌธ์ž์—ด์„ ์—ฐ๊ฒฐํ•˜์—ฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” Java ์†”๋ฃจ์…˜์„ ์ œ์‹œํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, [6, 10, 2]๋Š” "6210"์œผ๋กœ, [3, 30, 34, 5, 9]๋Š” "9534330"์œผ๋กœ ๋ฐ˜ํ™˜๋ฉ๋‹ˆ๋‹ค.
DriedPollack's avatar
Nov 28, 2024
[programmers] ๊ฐ€์žฅ ํฐ ์ˆ˜ - Java

๊ฐ€์žฅ ํฐ ์ˆ˜

๋ฌธ์ œ ์„ค๋ช…

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"

solution.java

import java.util.*; class Solution { public String solution(int[] numbers) { // ์ •๋ ฌ์„ ์œ„ํ•ด int ๋ฐฐ์—ด์„ String ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ String[] strNumbers = new String[numbers.length]; for (int i = 0; i < numbers.length; i++) { strNumbers[i] = String.valueOf(numbers[i]); } // comparator๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž์—ด ์ •๋ ฌ Arrays.sort(strNumbers, (a, b) -> (b + a).compareTo(a + b)); // ๊ฐ€์žฅ ํฐ ์ˆซ์ž๊ฐ€ "0"์ธ ๊ฒฝ์šฐ "0"์„ ๋ฐ˜ํ™˜ ex) [0, 0]์˜ ๊ฒฝ์šฐ if (strNumbers[0].equals("0")) { return "0"; } // ์ •๋ ฌ๋œ ๋ฌธ์ž์—ด์„ ์—ฐ๊ฒฐํ•˜์—ฌ ๊ฐ€์žฅ ๋งŽ์€ ์ˆ˜ ๋งŒ๋“ค๊ธฐ StringBuilder result = new StringBuilder(); for (String num : strNumbers) { result.append(num); } return result.toString(); } }
 

ํ•ต์‹ฌ ํ‚ค์›Œ๋“œ

  • Arrays.sort() ๋ฉ”์„œ๋“œ์—์„œ comparator์˜ ๊ฒฝ์šฐ (b + a)์™€ (a + b)๋ฅผ ๋น„๊ตํ•˜์—ฌ ์ˆœ์„œ๋ฅผ ๊ฒฐ์ •ํ•œ๋‹ค.
    • ์˜ˆ๋ฅผ ๋“ค์–ด a = "3" ๋ฐ b = "30"์ธ ๊ฒฝ์šฐ "303"๊ณผ "330"์„ ํ™•์ธํ•œ๋‹ค.
    • ์–‘์ˆ˜ ๊ฒฐ๊ณผ: (b + a)๊ฐ€ (a + b)๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ ์ •๋ ฌ๋œ ์ˆœ์„œ์—์„œ b๊ฐ€ a ์•ž์— ์™€์•ผ ํ•œ๋‹ค. ์Œ์ˆ˜ ๊ฒฐ๊ณผ: (a + b)๊ฐ€ (b + a)๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ ์ •๋ ฌ๋œ ์ˆœ์„œ์—์„œ a๊ฐ€ b ์•ž์— ์™€์•ผ ํ•œ๋‹ค. ๊ฒฐ๊ณผ ์—†์Œ: (a + b)๊ฐ€ (b + a)์™€ ๊ฐ™์œผ๋ฉด ์ˆœ์„œ๋Š” ์ค‘์š”ํ•˜์ง€ ์•Š๋‹ค.
 

๊ฒฐ๋ก !

ํ•ด๋‹น ๋ฌธ์ œ๋ฅผ ํ†ตํ•ด Arrays.sort() ๋ฉ”์„œ๋“œ๋ฅผ ใ…‡์‚ฌ์šฉํ•˜๋Š” ๋ฒ•์„ ์ตํž ์ˆ˜ ์žˆ์—ˆ๋‹ค.
 
Share article

More articles

See more posts

๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ปDriedPollack's Blog