티스토리 뷰
contains() in HashSet and ArrayList
Big-O notation for contains() in HashSet is O(1) which takes constant time and doesn't preserve the order. But, in ArrayList, It takes O(n) which is linear time and ensure the order of the entry.
Example Code
static int sockMerchant(int n, int[] ar) {
Set<Integer> color = new HashSet<>();
int pairs = 0;
for(int i = 0; i < n; i++){
if(!color.contains(ar[i])){//기존 element에 없으면
color.add(ar[i]); //set에 추가
}else{
pairs ++;
color.remove(ar[i]); //단 하나의 pair만 존재하게 하기 위해 기존 index삭제
}
}
return pairs;
}
|
contains() returns true if it is present in Set.
Reference
https://www.baeldung.com/java-hashset-arraylist-contains-performance
'Algorithms' 카테고리의 다른 글
Get the second smallest element in array (0) | 2019.09.07 |
---|---|
Counting Valley (0) | 2019.08.31 |
Insertion Sort (0) | 2019.08.01 |
Sequential Search Algorithm (Linear Search) (0) | 2019.07.30 |
Selection Sort (0) | 2019.07.27 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 프로그래머스
- equals()
- C++
- ... in Javascript
- java
- Collection Framework
- code refactoring
- javascript
- compareTo()
- 프로그래머스 알고리즘
- easy algorithm
- hackerrank javascript solution
- hackerrank javascript
- rest parameter
- HashMap
- 알고리즘
- math.max
- math.abs
- Javascript Algorithm
- algorithm
- easy javascript algorithm
- hackerrank
- string class in java
- repeat()
- hackerrank solution
- substring()
- Object type casting
- spring boot application
- HackerRank Algorithm
- 프로그래머스 알고리즘문제
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함