티스토리 뷰
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
- spring boot application
- 프로그래머스 알고리즘
- easy algorithm
- string class in java
- compareTo()
- repeat()
- code refactoring
- ... in Javascript
- C++
- HackerRank Algorithm
- algorithm
- hackerrank javascript
- 프로그래머스
- HashMap
- equals()
- math.abs
- java
- substring()
- javascript
- 프로그래머스 알고리즘문제
- hackerrank solution
- rest parameter
- hackerrank javascript solution
- Collection Framework
- 알고리즘
- easy javascript algorithm
- Object type casting
- math.max
- hackerrank
- Javascript 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 | 31 |
글 보관함