Post

[Programmers] 120583번 - 중복된 숫자 개수 [Java][C++]

[Programmers] 120583번 - 중복된 숫자 개수 [Java][C++]

문제 링크


1. 아이디어

정수가 담긴 배열 array와 정수 n이 매개변수로 주어질 때, arrayn이 몇 개 있는지를 return하는 문제로 배열을 순회하며 n과 일치하는지 개수만 세주면 된다.


2. 복잡도

시간복잡도공간복잡도
$O(N)$$O(1)$

3. 코드

풀이 [Java][C++]

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

        return cnt;
    }
}

count 함수를 활용하면 더 간단하게 표현할 수 있다.

1
2
3
4
5
6
7
8
#include <algorithm>
#include <vector>

using namespace std;

int solution(vector<int> array, int n) {
    return count(array.begin(), array.end(), n);
}

This post is licensed under CC BY 4.0 by the author.