Post

[Programmers] #120899 - 가장 큰 수 찾기 [Java][C++][Python]

[Programmers] #120899 - 가장 큰 수 찾기 [Java][C++][Python]

문제 링크


1. 아이디어

배열을 한 번 순회하면서 지금까지 본 최댓값과 그 인덱스를 함께 갱신했다. 모든 원소가 서로 다르므로 최댓값을 가지는 위치는 하나로 정해진다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(1)$

($N$ = array의 길이)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
    public int[] solution(int[] array) {
        int max = -1, idx = -1;
        for (int i = 0; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
                idx = i;
            }
        }

        return new int[]{max, idx};
    }
}
1
2
3
4
5
6
7
#include <bits/stdc++.h>
using namespace std;

vector<int> solution(vector<int> array) {
    int idx = max_element(array.begin(), array.end()) - array.begin();
    return {array[idx], idx};
}

std::max_element가 최댓값을 가리키는 이터레이터를 돌려주므로, begin()과의 거리로 인덱스를 구했다.

1
2
3
def solution(array):
    mx = max(array)
    return [mx, array.index(mx)]

max로 최댓값을 찾고 index로 그 위치를 되짚었다.


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