[Programmers] #181896 - 첫 번째로 나오는 음수 [Java][C++][Python]
정수 리스트에서 처음 나오는 음수의 인덱스를, 음수가 없으면 -1을 반환하는 워밍업 문제.
[Programmers] #181896 - 첫 번째로 나오는 음수 [Java][C++][Python]
1. 아이디어
num_list를 앞에서부터 순회하며 처음 만나는 음수의 인덱스를 반환하고, 끝까지 음수가 없으면 -1을 반환한다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = num_list의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
class Solution {
public int solution(int[] num_list) {
for (int i = 0; i < num_list.length; i++) {
if (num_list[i] < 0) return i;
}
return -1;
}
}
1
2
3
4
5
6
7
8
9
10
#include <bits/stdc++.h>
using namespace std;
int solution(vector<int> num_list) {
for (int i = 0; i < num_list.size(); i++) {
if (num_list[i] < 0) return i;
}
return -1;
}
1
2
def solution(num_list):
return next((i for i, x in enumerate(num_list) if x < 0), -1)
This post is licensed under CC BY 4.0 by the author.