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};
}
1
2
3
def solution(array):
    mx = max(array)
    return [mx, array.index(mx)]

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