Notice
Recent Posts
Recent Comments
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

I'm pine thank you and you?

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๊ฐ€์žฅ ํฐ ์ˆ˜ (Java) ๋ณธ๋ฌธ

Algorithm

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๊ฐ€์žฅ ํฐ ์ˆ˜ (Java)

SollyJ 2023. 3. 20. 17:20

๐Ÿ’œ ๋ฌธ์ œ

 


 

๐Ÿค” ๋ฌธ์ œ ๋ถ„์„

numbers ๋ฐฐ์—ด์„ ํŠน์ •ํ•œ ์กฐ๊ฑด์— ๋”ฐ๋ผ ์ •๋ ฌํ•˜์—ฌ ๋ถ™์ด๋Š” ๋ฌธ์ œ์ด๋‹ค.

์ž๋ฐ” ๋‚ด์žฅํ•จ์ˆ˜์ธ sort๋ฅผ ์ด์šฉํ•˜๋˜, ์ •๋ ฌ ์กฐ๊ฑด์„ Comparable ๋˜๋Š” Comparator๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ง์ ‘ ๊ตฌํ˜„ํ•˜์ž.

๋”๋ณด๊ธฐ
public interface Comparable<T>
int compareTo(T o)

์ž๊ธฐ ์ž์‹ ๊ณผ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋น„๊ต

Comparable์€ Lang ํŒจํ‚ค์ง€์— ์กด์žฌํ•˜์—ฌ import๋ฅผ ํ•˜์ง€ ์•Š๊ณ ๋„ ์‚ฌ์šฉ๊ฐ€๋Šฅํ•˜๋‹ค.

๋”๋ณด๊ธฐ
public interface Comparator<T>
int compare(T o1, T o2);

๋‘ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋น„๊ต

์ž๊ธฐ ์ž์‹ ์˜ ์ƒํƒœ๊ฐ€ ์–ด๋–ป๋˜ ์ƒ๊ด€์—†์ด ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋“ค์–ด์˜ค๋Š” ๋‘ ๊ฐ์ฒด๋ฅผ ๋น„๊ตํ•˜๋Š” ๊ฒƒ 

 


 

๐Ÿ“ ํ’€์ด

1. numbers ๋ฐฐ์—ด์„ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊ฟ”์„œ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ

2. ๋ฆฌ์ŠคํŠธ๋ฅผ Comparator๋ฅผ ์ด์šฉํ•˜์—ฌ ์ •๋ ฌ

๋ฐฉ๋ฒ•1

new Comparator<String>() {
	@Override
	public int compare(String o1, String o2) {
		int num1 = Integer.parseInt(o1 + o2);
		int num2 = Integer.parseInt(o2 + o1);

		return num2 - num1;
	}
}

์•ž๋’ค ๋ฌธ์ž์—ด์„ ๋”ํ•˜์—ฌ int๋กœ ๋ณ€ํ™˜ํ•œ ํ›„ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ

๋ฐฉ๋ฒ•2

new Comparator<String>(){
    @Override
    public int compare(String o1, String o2) { 
    	return (o2+o1).compareTo(o1+o2); 
    }
}

๋ฌธ์ž์—ด ์ž์ฒด๋ฅผ ๋น„๊ต 

๋ฌธ์ž์—ด "610"์™€ "106"๋ฅผ ๋น„๊ตํ•˜๋ฉด ๋ฌธ์ž ์ธ์ฝ”๋”ฉ ์ฒด๊ณ„์˜ ์ˆœ์„œ์— ๋”ฐ๋ผ ์ •๋ ฌ ๋œ๋‹ค.

์ด ๋ฐฉ๋ฒ•์ด ์ฝ”๋“œ๊ฐ€ ๋” ๊ฐ„๊ฒฐํ•˜๋‹ค.

3. ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฌธ์ž์—ด๋กœ appendํ•˜์—ฌ ์ถœ๋ ฅ

 


 

๐Ÿคฆ ์‹œํ–‰์ฐฉ์˜ค

๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ์˜ ์ฒซ๋ฒˆ์งธ ๊ฐ’์ด 0์ธ ๊ฒฝ์šฐ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค˜์•ผํ•œ๋‹ค.

๋งŒ์•ฝ {0, 0, 0, 0} ๋ผ๋ฉด 0๋งŒ ์ถœ๋ ฅํ•˜๋ฉด ๋˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 


 

๋”๋ณด๊ธฐ
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Programmers_๊ฐ€์žฅํฐ์ˆ˜ {
	public static void main(String[] args) {
		System.out.println(solution(new int[] {6, 10, 2}));
		System.out.println(solution(new int[] {3, 30, 34, 5, 9}));
	}

	private static String solution(int[] numbers) {
		StringBuilder answer = new StringBuilder();

		// ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊ฟ”์„œ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ
		ArrayList<String> strList = new ArrayList<>();

		for (int number : numbers) {
			strList.add(String.valueOf(number));
		}

		// ์ •๋ ฌ๊ธฐ์ค€์„ Comparator๋กœ ์ง์ ‘ ๊ตฌํ˜„
		Collections.sort(strList, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				int num1 = Integer.parseInt(o1 + o2);
				int num2 = Integer.parseInt(o2 + o1);

				return num2 - num1;
			}
		});

		if (strList.get(0).equals("0"))    // 0 ์˜ˆ์™ธ์ฒ˜๋ฆฌ
			answer.append("0");
		else
			strList.stream().forEach(s -> answer.append(s));

		return answer.toString();
	}
}