https://www.acmicpc.net/problem/10807
문제
총 N개의 정수가 주어졌을 때, 정수 v가 몇 개인지 구하는 프로그램을 작성하시오.
입력
첫째 줄에 정수의 개수 N(1 ≤ N ≤ 100)이 주어진다. 둘째 줄에는 정수가 공백으로 구분되어져있다. 셋째 줄에는 찾으려고 하는 정수 v가 주어진다. 입력으로 주어지는 정수와 v는 -100보다 크거나 같으며, 100보다 작거나 같다.
출력
첫째 줄에 입력으로 주어진 N개의 정수 중에 v가 몇 개인지 출력한다.
예제 입력1
11
1 4 1 2 4 2 4 2 3 4 4
2
예제 출력1
3
예제 입력2
11
1 4 1 2 4 2 4 2 3 4 4
5
예제 출력2
0
풀이
이번 문제는 쉬웠다.
정수들을 하나씩 검사하면서 정수 v의 개수를 헤아리면 된다.
코드 1 - 정답
internal class BOJ10807_개수_세기
{
static void Main(string[] args)
{
int N = int.Parse(Console.ReadLine());
string[] input = Console.ReadLine().Split(" ");
int v = int.Parse(Console.ReadLine());
int answer = 0;
for (int i = 0; i < N; i++)
{
if (int.Parse(input[i]) == v)
{
answer += 1;
}
}
Console.WriteLine(answer);
}
}
코드 2 - 오답
배열 인덱스를 정수라고 생각하고 코드를 짜봤다.
그런데 이렇게 코드를 짜니 -100과 0은 둘 다 인덱스가 0이 되어버리니 오답이 나온다.
internal class BOJ10807_개수_세기
{
static void Main(string[] args)
{
// 다른 풀이
int N = int.Parse(Console.ReadLine());
string[] input = Console.ReadLine().Split(" ");
int v = int.Parse(Console.ReadLine());
int answer = 0;
int[] arr = new int[300];
int index = 0;
for(int i = 0; i < N; i++)
{
index = int.Parse(input[i]);
if(index >= 0)
{
arr[index + 100] += 1;
}
else
{
arr[index + 100] += 1;
}
}
if(v >= 0)
{
Console.WriteLine(arr[v]);
}
else
{
Console.WriteLine(arr[v + 100]);
}
}
}
코드 3 - 정답
-100과 0이 인덱스 0이 되니, 음수든 양수든 상관없이 배열에 숫자 개수를 카운팅 할 때, "숫자 + 100"을 인덱스로 하면 된다.
internal class BOJ10807_개수_세기
{
static void Main(string[] args)
{
int N = int.Parse(Console.ReadLine());
string[] input = Console.ReadLine().Split(" ");
int v = int.Parse(Console.ReadLine());
int answer = 0;
int[] arr = new int[300];
int index = 0;
for(int i = 0; i < N; i++)
{
index = int.Parse(input[i]);
arr[index + 100] += 1;
}
Console.WriteLine(arr[v + 100]);
}
}
복습1 풀이 (5/6)
배열을 인덱스를 정수로, 배열의 값을 정수의 등장 횟수로 생각하고 문제를 풀면 된다.
복습1 코드 - 정답
using System.Text;
namespace 배열_구현
{
internal class BOJ10807_개수세기_복습1
{
static StreamReader sr = new StreamReader(Console.OpenStandardInput());
static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
static StringBuilder sb = new StringBuilder();
static void Main(string[] args)
{
int N = int.Parse(sr.ReadLine());
string[] input1 = sr.ReadLine().Split(" ");
int[] arr = new int[300];
int index = 0;
foreach(string s in input1)
{
index = int.Parse(s);
arr[index + 100]++;
}
int V = int.Parse(sr.ReadLine());
sb.Append(arr[V + 100]);
sw.WriteLine(sb.ToString());
sw.Close();
sr.Close();
}
}
}'자료구조, 코딩테스트 > 배열(Array)' 카테고리의 다른 글
| [코딩테스트] BOJ 11328 - Strfry (실패) (0) | 2026.04.02 |
|---|---|
| [코딩테스트] BOJ 13300 - 방 배정 (실패) (0) | 2026.04.01 |
| [코딩테스트] BOJ 3273 - 두 수의 합 (성공) (0) | 2026.03.30 |
| [코딩테스트] BOJ 1475 - 방 번호 (실패) (0) | 2026.03.25 |
| [코딩테스트] BOJ2577 - 숫자의 개수 (성공) (0) | 2026.03.25 |