剑指 Offer II 030. 插入、删除和随机访问都是 O(1) 的容器

竟然过了= =


class RandomizedSet {
    var map :[Int : Int]
    /** Initialize your data structure here. */
    init() {
        
        map = [Int:Int]()
        
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    func insert(_ val: Int) -> Bool {
        if let _ =  map[val] {
            return false
        }
        else{
            map[val] = val
            return true
        }

    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    func remove(_ val: Int) -> Bool {
        
        if let _ =  map[val] {
            map.removeValue(forKey: val)
            return true
        }
        else{
            return false
        }
        

    }
    
    /** Get a random element from the set. */
    func getRandom() -> Int {
     let array =  Array.init(map.values)
      let len = array.count
     return array[Int.random(in: 0..

你可能感兴趣的:(剑指 Offer II 030. 插入、删除和随机访问都是 O(1) 的容器)