[Programmers] 120813번 - 짝수는 싫어요 [Java][C++]
[Programmers] 120813번 - 짝수는 싫어요 [Java][C++]
1. 아이디어
정수 n 이하의 홀수가 오름차순으로 담긴 배열을 return하는 문제로 1 부터 n까지 반복 변수를 2칸씩 건너뛰며 배열에 담는 방식으로 해결했다.
2. 복잡도
| 시간복잡도 | 공간복잡도 |
|---|---|
| $O(N)$ | $O(1)$ |
N = 매개변수
n
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int[] solution(int n) {
int[] arr = new int[(n + 1) / 2];
int idx = 0;
for (int i = 1; i <= n; i += 2) {
arr[idx++] = i;
}
return arr;
}
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(int n) {
vector<int> v;
for (int i = 1; i <= n; i += 2) {
v.push_back(i);
}
return v;
}
This post is licensed under CC BY 4.0 by the author.