Hash Table

From_A_To_Z·2026년 1월 31일

알고리즘

목록 보기
10/10
  • 키(Key)와 값(Value)을 쌍으로 저장하고, 키를 이용해 빠르게 검색, 삽입, 삭제가 가능한 자료구조
  • 키를 해시 함수(Hash Function)로 변환 → 배열(버킷) 인덱스로 사용
  • 충돌(Collision)이 발생하면 별도의 처리 필요
  • 복잡도
    - 평균: O(1) (검색, 삽입, 삭제)
    - 최악: O(n) (충돌이 많거나 해시 함수 품질 낮음)

문제 유형

  1. 데이터베이스 인덱스
  2. 캐시 구현 (LRU 캐시 등)
  3. 중복 제거 / 카운팅
  4. 연결된 데이터 조회 (키로 빠르게 접근)

코드 예시

import java.util.HashMap;

public class HashTableExample {
    public static void main(String[] args) {
        // 키: String, 값: Integer
        HashMap<String, Integer> map = new HashMap<>();

        // 삽입
        map.put("apple", 3);
        map.put("banana", 2);
        map.put("orange", 5);

        // 검색
        System.out.println("apple의 값: " + map.get("apple")); // 3

        // 키 존재 여부 확인
        System.out.println("banana 존재? " + map.containsKey("banana")); // true

        // 삭제
        map.remove("banana");
        System.out.println("banana 존재? " + map.containsKey("banana")); // false

        // 모든 키-값 출력
        for (String key : map.keySet()) {
            System.out.println(key + " : " + map.get(key));
        }
    }
}
import java.util.HashMap;

public class WordCountExample {
    public static void main(String[] args) {
        String[] words = {"apple", "banana", "apple", "orange", "banana", "apple"};

        HashMap<String, Integer> countMap = new HashMap<>();

        for (String word : words) {
            countMap.put(word, countMap.getOrDefault(word, 0) + 1);
        }

        System.out.println(countMap); // {orange=1, banana=2, apple=3}
    }
}
profile
What goes around comes around.

0개의 댓글