美文网首页
剑指 Offer II 030. 插入、删除和随机访问都是 O(

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

作者: 邦_ | 来源:发表于2022-08-25 11:10 被阅读0次

    竟然过了= =

    
    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..<len)]
        
        }
    }
    
    
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:剑指 Offer II 030. 插入、删除和随机访问都是 O(

          本文链接:https://www.haomeiwen.com/subject/yqiagrtx.html