[Programmers] #120899 - 가장 큰 수 찾기 [Java][C++][Python]
[Programmers] #120899 - 가장 큰 수 찾기 [Java][C++][Python]
1. 아이디어
배열의 최댓값과 그 인덱스를 함께 반환하는 문제로, 원소에 중복이 없어 최댓값의 인덱스가 하나로 정해진다.
2. 코드
풀이 [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는 값이 아니라 이터레이터를 반환하므로 array.begin()을 빼서 인덱스로 바꿨다.
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.