💡 핵심 요약 (TL;DR)
'백준 10818 최소, 최대 풀이' 알고리즘 문제의 요구사항을 분석하고 최적의 자료구조와 연산 방식을 적용해 구현한 풀이다.
* 백준 java 풀이 모음을 확인했다.
문제 N개의 정수가 주어진다. 이때, 최솟값과 최댓값을 구하는 프로그램을 작성하시오.
풀이코드1: Math함수 사용하기
memory 116352 runtime 420
만약 br.close() 추가하면 memory 116588 runtime 404
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class Main { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer (br.readLine()); int min = Integer.parseInt(st.nextToken()); int max = min; for (int i = 1 ; i<n; i++){ int num = Integer.parseInt(st.nextToken()); min = Math.min(min, (num)); max = Math.max(max, (num)); } br.close(); System.out.println(min+" " +max); } }
풀이코드2: 배열정렬로 풀기
memory 114572 runtime 1000
br.close()추가 하면 memory 115624 runtime 1016
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Main { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer (br.readLine()); int i = 0 ; int [] arr = new int [n]; while (st.hasMoreTokens()) { arr[i] = Integer.parseInt(st.nextToken()); i++; } Arrays.sort(arr); System.out.println(arr[0 ] + " " + arr[n-1 ]); } }
풀이코드3: 배열없이 받은 문자 즉시 비교하기 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public class Main { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer (br.readLine()); int max = -1000001 ; int min = 1000001 ; while (st.hasMoreTokens()) { int val = Integer.parseInt(st.nextToken()); if (val>max) { max = val; } if (val<min) { min = val; } } System.out.println(min + " " + max); } }
백준의 다른 문제 풀이가 보고싶다면?
#Backjoon