코딩 테스트 풀이 12 - 개수 세기

배효림·2023년 3월 20일
0

코딩테스트

목록 보기
12/20

✔ 문제

https://www.acmicpc.net/problem/10807

💡 접근 방법

두 가지 방법으로 문제를 접근하였다.
1. 반복문을 써서 배열의 원소와 주어진 정수를 비교하여 count 를 증가시킨다
2. stream - filter, count 를 사용하는 방법

⭐ 코드

// 첫번째 방법 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // Input 처리
        int numCount = Integer.parseInt(br.readLine());
        String[] numArr = br.readLine().split(" ");
        int targetNum = Integer.parseInt(br.readLine());

        int[] values = Arrays.stream(numArr)
                .mapToInt(Integer::parseInt)
                .toArray();

        int count = 0;
        for (int value : values)
        {
            if (value == targetNum)
                ++count;
        }

        System.out.println(count);

    }
}
// 두번째 방법 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main
{
   public static void main(String[] args) throws IOException
   {
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

       // Input 처리
       int numCount = Integer.parseInt(br.readLine());
       String[] numArr = br.readLine().split(" ");
       int targetNum = Integer.parseInt(br.readLine());

       long count = Arrays.stream(numArr).map(Integer::parseInt).filter(h -> h ==targetNum).count();

       System.out.println(count);

   }
}
profile
항상 위를 바라보는 프로그래머

0개의 댓글