728x90
Hash Table
- Hash table은 효율적 탐색을 위한 자료구조
- key-value 형태로 데이터 입력 받음
- HashMap과 다르게 null 입력 불가능
- 키는 중복이 안되지만 값은 중복 허용
Hash Map
- key와 value는 모두 객체 형태
- key와 value 자료형 별개 가능
- key를 이용해 value에 접근 가능
- HashMap<T, P> hashMap = new HashMap<T, P>();
- get(key)를 하여 key가 존재하지 않을 때 null을 return 해줌
- → 해당 기능을 통해 값이 있는지 없는지 판단을 바로 할 수 있음
- -10^9 ~ 10^9 는 int 형의 범위
import java.util.*;
class Solution {
public int longestConsecutive(int[] nums) {
int result = 0;
int tmpN = Integer.MIN_VALUE;
Set<Integer> set = new HashSet<>();
for(int n : nums){
set.add(n);
}
Map<Integer, Boolean> map = new HashMap<>();
List<Integer> list = new ArrayList<>(set);
Collections.sort(list);
for(int n: set){
map.put(n,true);
}
for(int n: list){
if(tmpN >= n){
continue;
}
int tmp = 1;
int next = n+1;
while(map.get(next) != null){
next += 1;
tmp += 1;
}
tmpN = next-1;
if(tmp > result){
result = tmp;
}
}
return result;
}
}
문제 : https://leetcode.com/problems/longest-consecutive-sequence/description/
Longest Consecutive Sequence - LeetCode
Can you solve this real interview question? Longest Consecutive Sequence - Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. Example 1: Input:
leetcode.com
출처 : 출처 : https://www.inflearn.com/course/코딩테스트-입문-파이썬/
코딩테스트 [ ALL IN ONE ] - 인프런 | 강의
코딩테스트 [ ALL IN ONE ] ✔️ 강의 하나로 끝내기, - 강의 소개 | 인프런
www.inflearn.com
'기초 학습 > 자료구조와 알고리즘' 카테고리의 다른 글
Queue / Stack(큐/스택) (0) | 2023.05.01 |
---|---|
List(리스트) (0) | 2023.03.30 |
Two Pointer (투포인터) (0) | 2023.03.27 |
자료구와 알고리즘 (1) | 2023.03.26 |