알고리즘/codility
[codility]Lesson 6 Sorting - Distinct
055055
2019. 9. 22. 21:43
반응형
https://app.codility.com/programmers/lessons/6-sorting/distinct/
Distinct coding task - Learn to Code - Codility
Compute number of distinct values in an array.
app.codility.com
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].
Copyright 2009–2019 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
배열 A에서 중복된 값을 제거하고 남은 값의 길이를 리턴하는 문제 입니다.
// 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) {
// write your code in Java SE 8
HashMap result = new HashMap();
for(int b : A){
result.put(b,b);
}
return result.size();
}
}
HashMap을 사용하였습니다. HashMap은 중복된 key값을 허용하지 않습니다.
비슷하게 HashSet을 사용할 수도 있는데 HashSet은 중복된 value값을 허용하지 않습니다.
다른 방법으로 Stream을 사용해 봤습니다.
// 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) {
// write your code in Java SE 8
int [] result = Arrays.stream(A).distinct().toArray();
return result.length;
}
}
Performance tests에서 Timeout error에 걸리네요.
stream으로 사용하는 방법이 성능면에서는 조금 더 안좋은 것 같습니다.
반응형