티스토리 뷰

Algorithm/Leetcode

460. LFU Cache

소농배 2025. 3. 19. 15:02
class LFUCache {

    private final int capacity;

    // <key, value>
    Map<Integer, Integer> cache = new HashMap<>();

    // <key, frequency>
    Map<Integer, Integer> frequencyMap = new HashMap<>();

    // <frequency, <key>>
    Map<Integer, LinkedHashSet<Integer>> accessSequenceMap = new HashMap<>();

    // <frequency> : 현존하는 frequency 를 저장
    Set<Integer> frequencySet = new HashSet<>();

    public void expireCache() {
        Integer smallestFrequency = null;
        for (Integer frequency : frequencySet) {
            if (smallestFrequency == null) {
                smallestFrequency = frequency;
            } else {
                if (frequency < smallestFrequency) {
                    smallestFrequency = frequency;
                }
            }

        }

        LinkedHashSet<Integer> smallestFrequencyKeys = accessSequenceMap.get(smallestFrequency);
        Integer lastAccessedKey = null;
        for (Integer key : smallestFrequencyKeys) {
            lastAccessedKey = key;
        }

        // Expire Target Key
        cache.remove(lastAccessedKey);
        frequencyMap.remove(lastAccessedKey);
        smallestFrequencyKeys.remove(lastAccessedKey);
        if (smallestFrequencyKeys.isEmpty()) {
            frequencySet.remove(smallestFrequency);
        }
    }

    public void updateFrequency(int key) {
        Integer frequency = frequencyMap.get(key);
        if (frequency == null) {
            // first access
            frequency = 0;
        } else {
            if (accessSequenceMap.get(key).size() == 1) {
                // 해당 frequency 에 해당 키만 존재
                frequencySet.remove(key);
            }
            accessSequenceMap.get(frequency).remove(key);
        }
        frequency++;

        frequencySet.add(frequency);
        frequencyMap.put(key, frequency);

        LinkedHashSet<Integer> newFrequencySet = accessSequenceMap.get(frequency);
        if (newFrequencySet == null) {
            newFrequencySet = new LinkedHashSet<>();
        }
        newFrequencySet.add(key);
        accessSequenceMap.put(frequency, newFrequencySet);
    }

    public LFUCache(int capacity) {
        this.capacity = capacity;
    }

    public int get(int key) {
        Integer value = cache.get(key);
        if (value != null) {
            updateFrequency(key);
            return value;
        } else {
            return -1;
        }
    }

    public void put(int key, int value) {
        if (this.capacity == cache.size()) {
            expireCache();
        }
        cache.put(key, value);
    }
}

'Algorithm > Leetcode' 카테고리의 다른 글

977. Squares of a Sorted Array  (0) 2025.03.19
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
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
글 보관함