Data structure: insert, remove, contains, get random element, all at O(1)

后端 未结 14 735
别跟我提以往
别跟我提以往 2020-11-29 14:53

I was given this problem in an interview. How would you have answered?

Design a data structure that offers the following operations in O(1) time:

  • inse
14条回答
  •  伪装坚强ぢ
    2020-11-29 15:14

    Cant we do this using HashSet of Java? It provides insert, del, search all in O(1) by default. For getRandom we can make use of iterator of Set which anyways gives random behavior. We can just iterate first element from set without worrying about rest of the elements

    public void getRandom(){
        Iterator sitr = s.iterator();
        Integer x = sitr.next();    
        return x;
    }
    

提交回复
热议问题