Post

[Programmers] #181896 - 첫 번째로 나오는 음수 [Java][C++][Python]

[Programmers] #181896 - 첫 번째로 나오는 음수 [Java][C++][Python]

문제 링크


1. 아이디어

처음 만나는 음수에서 멈추면 되고, 0은 음수가 아니므로 0 미만만 음수로 본다.


2. 코드

풀이 [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)

next의 두 번째 인자로 -1을 넘겨서 음수가 없을 때 예외 대신 -1이 나오게 했다.


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