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

문제

N개의 정수가 주어진다. 이때, 최솟값과 최댓값을 구하는 프로그램을 작성하시오.

  • 입출력예시
1
2
3
4
5
6
//입력
5
20 10 35 30 7

//출력
7 35




풀이코드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());

// sol1 Math함수 사용하기
// memory 116352 runtime 420 -> br.close()하면 memory 116588 runtime 404

int min = Integer.parseInt(st.nextToken());
int max = min;
for(int i=1; i<n; i++){ //i가 0이 아닌 1인 이유는 min, max 선언할때 5개의 숫자중 첫번째 토큰을 사용했기때문
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
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());


// sol2 배열정렬로 풀기
// memory 114572 runtime 1000 -> br.close()하면 memory 115624 runtime 1016
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());

// sol3 배열없이 받은 문자 즉시 비교하기
// memory 107004 runtime 472
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);
}
}




백준의 다른 문제 풀이가 보고싶다면?

Comments