๋ฌธ์
์ด N๊ฐ์ ์ ์๊ฐ ์ฃผ์ด์ก์ ๋, ์ ์ v๊ฐ ๋ช ๊ฐ์ธ์ง ๊ตฌํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค.
์ ๋ ฅ
์ฒซ์งธ ์ค์ ์ ์์ ๊ฐ์ N(1 ≤ N ≤ 100)์ด ์ฃผ์ด์ง๋ค. ๋์งธ ์ค์๋ ์ ์๊ฐ ๊ณต๋ฐฑ์ผ๋ก ๊ตฌ๋ถ๋์ด์ ธ์๋ค. ์ ์งธ ์ค์๋ ์ฐพ์ผ๋ ค๊ณ ํ๋ ์ ์ v๊ฐ ์ฃผ์ด์ง๋ค. ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ ์ ์์ v๋ -100๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์ผ๋ฉฐ, 100๋ณด๋ค ์๊ฑฐ๋ ๊ฐ๋ค.
11
1 4 1 2 4 2 4 2 3 4 4
2
์ถ๋ ฅ
์ฒซ์งธ ์ค์ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง N๊ฐ์ ์ ์ ์ค์ v๊ฐ ๋ช ๊ฐ์ธ์ง ์ถ๋ ฅํ๋ค.
3
1. ์ฒ์ ์ฝ๋ (104ms)
import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int v = Integer.parseInt(br.readLine());
int[] nArray = new int[N];
int count = 0;
for (int i = 0; i < N; i++) {
nArray[i] = Integer.parseInt(st.nextToken());
}
for (int i = 0; i < N; i++) {
if (nArray[i] == v) {
count++;
}
}
System.out.println(count);
}
}
๋ง ๊ทธ๋๋ก for๋ฌธ์ ์ด์ฉํด ๊ฐ์์ธ count๋ฅผ ์ฌ๋ฆฌ๋ ์ฝ๋์ด๋ค.
๊ทธ๋ฐ๋ฐ ์ด๊ฑฐ ๋ง๊ณ ์ข ๋ ์๋ฝํ๊ฒ ์๋ ํ๊ตฌํด๋ดค๋ค.
2. ๋ฐฐ์ด ์์ฐ๋ฉด ์๋๋? => ์ฅ ์๊ฐ ๋๊ฑธ๋ฆผ
import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int v = Integer.parseInt(br.readLine());
int count = 0;
for (int i = 0; i < N; i++) {
if (Integer.parseInt(st.nextToken()) == v) {
count++;
}
}
System.out.println(count);
}
}
๋ฐฐ์ด์ ๋นผ๋ฒ๋ ธ๋ค.
๊ทธ๋ฐ๋ฐ ๋ฐฑ์ค์์๋ ์ด๊ฒ ์๊ฐ์ ์ฐจ์ด๊ฐ ์๊ณ , ๋ฉ๋ชจ๋ฆฌ๋ ๋ ์ผ๋ค.
์์ง? ๋ฐฐ์ด์ด ๋ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ธ๊ฑฐ๋ผ๊ณ ์๊ฐํ๋๋ฐ.
|
๊ทธ๋ ๋ค๊ณ ํ๋ค. ํ๋ฒ ๋ฉ๋ชจ๋ฆฌ ๋ด๊บผ์ผ! ํ๋๊ฑฐ๋
์คํธํ ์ ๊ฒ๋ ๋ด๊บผ ์ ๊ฒ๋ ๋ด๊บผ ํ๋๊ฑฐ๋์ ์ฐจ์ด.
3. for๋ฌธ์ ํ๋ฒ๋ง ์ฐ๊ณ ์ถ์์
import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] nArray = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine());
int v = Integer.parseInt(br.readLine());
int count = 0;
for (int i = 0; i < N; i++) {
nArray[i] = Integer.parseInt(st.nextToken());
if (nArray[i] == v) {
count++;
}
}
System.out.println(count);
}
}
4. ํ ํฐ ์์ธ๋ญ (๋น์ฐํจ. ์๊ฐ ๋ ๊ฑธ๋ฆผ)
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
String[] input = br.readLine().split(" ");
int v = Integer.parseInt(br.readLine());
int count = 0;
for (int i = 0; i < N; i++) {
if (Integer.parseInt(input[i]) == v) {
count++;
}
}
System.out.println(count);
}
}