[BaekJoon] #10818 - 최소, 최대 [Java][C++]
[BaekJoon] #10818 - 최소, 최대 [Java][C++]
1. 아이디어
주어진 $N$개의 정수 중 최솟값과 최댓값을 구하는 문제로 직접 구현할 경우 최솟값은 가능한 최댓값 이상으로, 최댓값은 가능한 최솟값 이하로 초기화한 후 비교를 통해 갱신하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = 입력값 n. C++는 벡터에 담아 공간 $O(N)$)
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
int min = 1_000_000;
int max = -1_000_000;
st = new StringTokenizer(br.readLine());
while (n-- > 0) {
int x = Integer.parseInt(st.nextToken());
min = Math.min(min, x);
max = Math.max(max, x);
}
System.out.println(min + " " + max);
}
}
Math 유틸리티 클래스의 min, max 메서드를 활용했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
auto [mn_it, mx_it] = minmax_element(v.begin(), v.end());
cout << *mn_it << ' ' << *mx_it;
}
std::minmax_element 함수로 벡터에서 최솟값을 가리키는 iterator와 최댓값을 가리키는 iterator를 받는 방식으로 해결했다.
This post is licensed under CC BY 4.0 by the author.