Post

[백준] 10818번 - 최소, 최대 [Java][C++]

[백준] 10818번 - 최소, 최대 [Java][C++]

문제 링크


1. 문제 풀이

주어진 $N$ 개의 정수 중 최솟값과 최댓값을 구하는 문제로 직접 구현할 경우 최솟값은 가능한 최댓값 이상으로, 최댓값은 가능한 최솟값 이하로 초기화한 후 비교를 통해 갱신해주면 된다.


2. 코드

1. 구현 [Java]

Math 유틸리티 클래스의 min, max 메서드를 활용했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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[] arr = new int[N];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        int min = 1_000_000;
        int max = -1_000_000;
        for (int num : arr) {
            min = Math.min(min, num);
            max = Math.max(max, num);
        }

        System.out.println(min + " " + max);
    }
}

2. 구현 [C++]

minmax_element 함수로 벡터에서 최솟값을 가리키는 iterator 와 최댓값을 가리키는 iterator 를 받는 방식으로 해결했다.

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(false);
    cin.tie(nullptr);

    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;
}

3. 풀이 정보

1. 구현 [Java]

언어시간메모리코드 길이
Java 11452 ms92484 KB698 B

2. 구현 [C++]

언어시간메모리코드 길이
C++ 17104 ms5928 KB297 B

This post is licensed under CC BY 4.0 by the author.