Problem
https://app.codility.com/programmers/lessons/6-sorting/distinct/
Write a function
class Solution { public int solution(int[] A); }
that, given an array A consisting of N integers, returns the number of distinct values in array A.
For example, given array A consisting of six elements such that:
A[0] = 2 A[1] = 1 A[2] = 1 A[3] = 2 A[4] = 3 A[5] = 1
the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.
Write an efficient algorithm for the following assumptions:
- N is an integer within the range [0..100,000];
- each element of array A is an integer within the range [−1,000,000..1,000,000].
배열의 중복제거이다. Set 인터페이스가 떠오르고 해당 인터페이스를 상속받는 HashSet과 TreeSet 구현 클래스가 떠오른다면 성공.
https://coding-factory.tistory.com/554
Solution
// you can also use imports, for example:
import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
if(A.length == 0) return 0;
HashSet<Integer> set = new HashSet<>();
for(int su : A){
set.add(su);
}
return set.size();
}
}
HashSet 클래스를 이용한 중복제거.
이후 해당 객체의 사이즈를 리턴하면 된다.
Learn Point
1. 자료구조나 알고리즘 관련 문제는 특정 클래스를 안쓰고, 최대한 단순하게 해야한다는 강박관념이 생각을 앗아간 사례이다. ( 시간복잡도... )
'Algorithm > JAVA' 카테고리의 다른 글
| Algorithm Study - 002 (0) | 2021.06.02 |
|---|---|
| Algorithm Study - 001 (0) | 2021.06.02 |
| 숫자 반전 알고리즘 (0) | 2021.06.02 |