본문 바로가기

프로그래머스 코딩(자바)/Level 0

Programmers Level 0 - 중복된 숫자 개수

728x90

중복된 숫자 개수

 
문제 설명

정수가 담긴 배열 array와 정수 n이 매개변수로 주어질 때, array에 n이 몇 개 있는 지를 return 하도록 solution 함수를 완성해보세요.

 

제한사항
  • 1 ≤ array의 길이 ≤ 100
  • 0 ≤ array의 원소 ≤ 1,000
  • 0 ≤ n ≤ 1,000
 

입출력 예
array n result       
[1, 1, 2, 3, 4, 5] 1 2
[0, 2, 3, 4] 1 0

 


입출력 예 설명

입출력 예 #1

  • [1, 1, 2, 3, 4, 5] 에는 1이 2개 있습니다.

입출력 예 #2

  • [0, 2, 3, 4] 에는 1이 0개 있습니다.

[ 풀이 1 ]

1
2
3
4
5
6
7
8
9
class Solution {
    public int solution(int[] array, int n) {
        int answer = 0;
        for(int t : array){
            if(n==t) answer++;
        }
        return answer;
    }
}
cs

 

제일 이해하기 쉬운 코드이다.
배열을 반복하며 같을때만 숫자를 증가시켜 준다. 

 

[ 풀이 2 ]

1
2
3
4
5
class Solution {
    public int solution(int[] array, int n) {
       return (int) Arrays.stream(array).filter((value) -> value==n).count();
    }
}
cs

 

Stream을 배웠다면 위와 같이 1줄로도 가능하다.

return (int) Arrays.stream(array) // int 배열을 Arrays.stream() 메서드로 IntStrem으로 만든다.
             .filter((value)
-> value==n)  // filter() 메서드로 n과 같은 값만 걸러준다.
             .count(); // count() 메서드로 개수를 센다.  리턴 타입이 long이므로 int로 형변환해야 함 

 

[ 풀이 3

1
2
3
4
5
class Solution {
    public int solution(int[] array, int n) {
       return IntStream.of(array).filter((value) -> value==n).toArray().length;
    }
}
cs

 

Stream을 배웠다면 위와 같이 1줄로도 가능하다.

return IntStream.of(array) // int 배열을 IntStream.of() 메서드로 IntStrem으로 만든다.
       .filter((value) 
-> value==n)  // filter() 메서드로 n과 같은 값만 걸러준다.
      .toArray().length;  // toArray() 메서드로  배열로 만들고 length 속성으로 배열 길이 구함
                          // 형변환 안함

[ 풀이 4 ]

 

1
2
3
4
5
class Solution {
    public int solution(int[] array, int n) {
       return Collections.frequency(Arrays.stream(array).boxed().collect(Collectors.toList()),n);
    }
}
cs

 

Collectors.toList()                   // Stream을 List로 만들어 줍니다.

Arrays.stream(array)                  // IntStream으로 만들고
.boxed()                              // IntStream을 Stream<Integer>로 만들어 주고
.collect(Collectors.toList())         // List<Integer>로 만들어 줍니다.


Collections.frequency(Collection 객체, 기대하는 객체)  : 일치하는 개수를 구해줍니다.

 

한가지 방법이 아니라 여러 방법으로 해결을 시도하는 노력이 필요하다. 그것이 프로그래머의 삶이다.

 

728x90