[BaekJoon] #10807 - 개수 세기 [Java][C++]
[BaekJoon] #10807 - 개수 세기 [Java][C++]
1. 아이디어
$N$개의 정수와 정수 $v$가 주어졌을 때, $N$개의 정수 중에 $v$가 몇 개 포함됐는지 구하는 간단한 문제다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = 입력값 n. C++는 벡터에 담아 공간 $O(N)$)
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
int v = Integer.parseInt(br.readLine());
int cnt = 0;
while (n-- > 0) {
int x = Integer.parseInt(st.nextToken());
if (x == v) cnt++;
}
System.out.println(cnt);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
int x;
cin >> x;
cout << count(v.begin(), v.end(), x);
}
std::count 함수를 활용해 벡터의 전체 구간에서 개수를 셌다.
This post is licensed under CC BY 4.0 by the author.