본문 바로가기

CodingTest Practice

[Codility 문풀] Distinct

Codility 문제 - Distinct

배열에 저장된 서로 다른 수의 개수를 반환

 

■ 문제 풀이

1) 문풀 설명
- 길이가 N인 배열에 저장되어 있는 서로 다른 수의 갯수를 반환

2) 예제
배열 A = [2, 1, 1, 2, 3, 1] 가 있다. 이 배열 속 요소에서 서로 다른 값은 3개이다 (1, 2, 3)
즉 결과 값으로 3을 반환하게 된다.

3) 힌트
중복을 허용하지 않는 HashSet을 활용하여 배열의 각 요소를 Hashset 객체에 담는다.

 

import java.util.HashSet;

public class Distinct {
    static int solution(int[] a){
        HashSet<Integer> set = new HashSet<>();
        for(int i=0; i<a.length; i++){
            set.add(a[i]);
        }

        return set.size();
    }
    public static void main(String[] args) {
        int[] a = {2, 1, 1, 2, 3, 1};
        int result = solution(a);
        System.out.println("return count : " + result);
    }
}

 

'CodingTest Practice' 카테고리의 다른 글

[Codility 문풀] Nesting  (0) 2022.01.10
[Codility 문풀] Brackets  (0) 2022.01.10
[codingTest] anagram  (0) 2022.01.07
[Codility 문풀] MaxProductOfThree  (0) 2022.01.06
Codility 문풀 - Fish  (0) 2022.01.03