[leetcode #380] Insert Delete GetRandom O(1)

Seongyeol Shin·2021년 10월 21일
0

leetcode

목록 보기
56/196
post-thumbnail

Problem

Implement the RandomizedSet class:

・ RandomizedSet() Initializes the RandomizedSet object.
・ bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
・ bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
・ int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

You must implement the functions of the class such that each function works in average O(1) time complexity.

Example 1:

Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]

Explanation
・ RandomizedSet randomizedSet = new RandomizedSet();
・ randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
・ randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
・ randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
・ randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
・ randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
・ randomizedSet.insert(2); // 2 was already in the set, so return false.
・ randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

Constraints:

・ -2³¹ <= val <= 2³¹ - 1
・ At most 2 * 10⁵ calls will be made to insert, remove, and getRandom.

There will be at least one element in the data structure when getRandom is called.

Idea

재미있는 문제다. RandomizedSet이라는 자료구조를 구현해야 하는데, Collections에서 지원되는 insert, remove 외에 getRandom이라는 연산을 구현해야 하는게 어렵다. Java에서 지원해주는 Set이 index를 지원하지 않기 때문에 O(1)으로 random한 element를 얻는 것은 기본 라이브러리 함수로는 불가능하다. 그래서 RandomizedSet의 자료구조로 set을 사용할 수는 없다.

O(1)으로 구현해야 하는데다, random access도 가능해야 하기 때문에 index로 접근 가능한 자료구조인 list를 활용한다. 대신, list에서 insert와 delete를 O(1)으로 구현하려면 index를 따로 저장할 자료구조 또한 필요하기 때문에 map도 활용해야 한다. map은 key가 set에 들어갈 수이며, value를 해당 숫자가 list에 존재하는 위치로 지정한다. 마지막으로 random access를 위한 Random 객체도 생성한다.

insert 함수에서는 주어진 수가 map에 있는 경우 false를 리턴한다. 없을 경우 list에 숫자를 추가하고, map에 해당 수를 key로, list의 마지막 index를 value로 저장한다.

remove 함수에서는 주어진 수가 map에 없을 경우 false를 리턴한다. 주어진 수의 index를 찾아 리스트와 맵에서 각각 제거한다. 이 때 마지막 index에 있던 수는 따로 저장을 한 뒤 제거된 수의 index에 추가한다. 맵에 저장되어있던 index도 함께 바꿔줘야 한다.

getRandom 함수는 list의 크기만큼의 범위에 해당하는 난수를 얻고 해당 난수를 index로 하여 list에서 값을 넘겨주면 된다.

Class를 구현하는 문제라 그런지 실행할 때마다 결과가 매번 큰 차이가 나게 된다. 제일 잘 나왔을 때 결과만 첨부해야지.

Solution

class RandomizedSet {
    Map<Integer, Integer> map;
    List<Integer> list;
    Random random;

    public RandomizedSet() {
        map = new HashMap<Integer, Integer>();
        list = new ArrayList<Integer>();
        random = new Random();
    }

    public boolean insert(int val) {
        if (map.containsKey(val))
            return false;

        list.add(val);
        map.put(val, list.size()-1);

        return true;
    }

    public boolean remove(int val) {
        if (!map.containsKey(val))
            return false;

        int index = map.get(val);
        int lastElement = list.get(list.size()-1);
        list.remove(index);
        map.remove(val);

        if (index != list.size()) {
            list.remove(list.size()-1);
            map.remove(lastElement);
            list.add(index, lastElement);
            map.put(lastElement, index);
        }

        return true;
    }

    public int getRandom() {
        int index = random.nextInt(list.size());

        return list.get(index);
    }
}

Reference

https://leetcode.com/problems/insert-delete-getrandom-o1/

profile
서버개발자 토모입니다

0개의 댓글