티스토리 뷰
반응형
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으로 사용하는 방법이 성능면에서는 조금 더 안좋은 것 같습니다.
반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Slack
- 뱅크샐러드
- vue.js
- spring-boot-starter-data-redis
- gradle
- effectivejava
- update query multi row
- 이것이 자바다
- 싱글턴
- update query
- SpringBoot
- 뱅크샐러드 유전자
- multiple row update
- springboot https
- update set multiple
- visual studio code
- update query set multiple
- 이펙티브자바
- update set multi
- 뱅셀 유전자
- 몽고DB 완벽가이드
- update query mutiple row
- 슬랙봇
- 그레이들
- 슬랙
- 슬랙 /
- 업데이트 쿼리
- 다중 업데이트
- MSSQL
- java
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함