[Programmers] #120824 - 짝수 홀수 개수 [Java][C++][Python]
[Programmers] #120824 - 짝수 홀수 개수 [Java][C++][Python]
1. 아이디어
num_list를 순회하며 각 원소를 2로 나눈 나머지로 홀수 개수를 세고, 전체 길이에서 이를 빼 짝수 개수를 구한 뒤 [짝수 개수, 홀수 개수] 순서로 반환하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = num_list의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
class Solution {
public int[] solution(int[] num_list) {
int odd = 0;
for (int x : num_list) {
if (x % 2 != 0) odd++;
}
return new int[]{num_list.length - odd, odd};
}
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<int> num_list) {
int odd = 0;
for (int x : num_list) {
if (x % 2) odd++;
}
return {(int)num_list.size() - odd, odd};
}
1
2
3
def solution(num_list):
odd = sum(x % 2 for x in num_list)
return [len(num_list) - odd, odd]
This post is licensed under CC BY 4.0 by the author.