본문 바로가기

[BOJ] - JAVA

[백준] 10818 : 최소, 최대 JAVA 풀이

배열을 사용한 코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;

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());
        int min, max, idx=0;
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");
        
        int[] arr = new int[N];
        while(st.hasMoreTokens()){
            arr[idx] = Integer.parseInt(st.nextToken());
            idx++;
        }
        
        min = arr[0];
        max = arr[0];
        
        for(int i=1;i<N;i++){
            if(min>arr[i]){
                min = arr[i];
            }
            if(max<arr[i]){
                max = arr[i];
            }
        }
        
        System.out.println(min+" "+max);
    }
}

 

배열을 쓰지 않고 바로 비교하는 코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class Main{
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int max = -1000001;
		int min = 1000001;
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");
       
        while(st.hasMoreTokens()){
            int val = Integer.parseInt(st.nextToken());
            if(min>val){
                min = val;
            }
            if(max<val){
                max = val;
            }
        }
        System.out.println(min+" "+max);
    }
}