PS/BaekJoon

2751 JAVA ์ˆ˜ ์ •๋ ฌํ•˜๊ธฐ 2

chaerlo127 2022. 7. 3. 22:50
728x90


import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		StringBuilder sb = new StringBuilder();
		// String ๊ณผ ๋ฌธ์ž์—ด์„ ๋”ํ•  ๋•Œ ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ, ๊ธฐ์กด์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋”ํ•˜๋Š” ๋ฐฉ์‹
		// ์†๋„๊ฐ€ ๋น ๋ฅด๋ฉฐ, ์ƒ๋Œ€์ ์œผ๋กœ ๋ถ€ํ•˜๊ฐ€ ์ ์œผ๋ฏ€๋กœ ๊ธด ๋ฌธ์ž์—ด์„ ๋”ํ•˜๋Š” ์ƒํ™ฉ์—์„œ ์‚ฌ์šฉ
		// StringBuffer: ๊ณตํ†ต ๋ฉ”์†Œ๋“œ ๋™๊ธฐํ™” ๋ฉ€ํ‹ฐ ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ๋งŒ <๊ฐ’์ด ์˜ˆ์ƒ์น˜ ๋ชปํ•˜๊ฒŒ ๋ณ€๊ฒฝ๋˜๋Š” ๊ฒƒ์„ ๋ฐฉ์ง€>
		// StringBuilder: ๊ทธ์™ธ์˜ ๊ธฐ๋Šฅ์€ StringBuilder๊ฐ€ ๋›ฐ์–ด๋‚จ.
		ArrayList<Integer> a = new ArrayList<>();
		int num = scanner.nextInt();
		for(int i = 0; i<num; i++) {
			a.add(scanner.nextInt());
		}
		scanner.close();
		
		Collections.sort(a);
		//Arrays.sort(a)๋Š” quicksort์ด๋ฏ€๋กœ ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(nlogn)์ด์ง€๋งŒ worst case๋Š” O(n^2)์ด ๋  ์ˆ˜ ์žˆ๋‹ค.
		//Collections๋Š” ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ์ตœ๋Œ€ O(nlogn)์ด๋‹ค.
		for(int i = 0; i<num; i++) {
			sb.append(a.get(i)).append("\n");
			// ๋งŽ์€ ๋ฌธ์ž์—ด์„ ์—ฐ๊ฒฐํ•˜๋ฉด ์ค‘๊ฐ„ ๋ฌธ์ž์—ด ๊ฐ์ฒด๊ฐ€ ์ƒ์„ฑ๋˜์–ด ๋น„ํšจ์œจ์ ์ธ ์ฝ”๋“œ๊ฐ€ ๋งŽ์ด ์ƒ์„ฑ๋œ๋‹ค.
			// String ๊ฐ์ฒด๋Š” ๋ณ€๊ฒฝ์ด ๋ถˆ๊ฐ€๋Šฅ ํ•œ ๊ฒƒ๊ณผ ๋‹ฌ๋ฆฌ, StringBuffer๋Š” ๋ณ€๊ฒฝ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
		}
		System.out.println(sb);
	}
}

 

[์ถœ์ฒ˜] : StringBuilder

https://hardlearner.tistory.com/288

https://onlyfor-me-blog.tistory.com/317

728x90