为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode380. 常数时间插入、删除和获取随机元素 | Insert Delete GetRandom O(1)

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Design a data structure that supports all following operations in averageO(1) time. 

  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. 

Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。

  1. insert(val):当元素 val 不存在时,向集合中插入该项。
  2. remove(val):元素 val 存在时,从集合中移除该项。
  3. getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。

示例 :

// 初始化一个空的集合。
RandomizedSet randomSet = new RandomizedSet();

// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomSet.insert(1);

// 返回 false ,表示集合中不存在 2 。
randomSet.remove(2);

// 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomSet.insert(2);

// getRandom 应随机返回 1 或 2 。
randomSet.getRandom();

// 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomSet.remove(1);

// 2 已在集合中,所以返回 false 。
randomSet.insert(2);

// 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
randomSet.getRandom();

260ms
 1 class RandomizedSet {
 2     var dic : [Int:Int] // value - key
 3     var arr : [Int] //value
 4     /** Initialize your data structure here. */
 5     init() {
 6         arr = [Int]()
 7         dic = [Int:Int]()
 8     }
 9     
10     /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
11     func insert(_ val: Int) -> Bool {
12         if dic[val] != nil { return false}
13         arr.append(val)
14         dic[val] = arr.count - 1
15         return true
16     }
17     
18     /** Removes a value from the set. Returns true if the set contained the specified element. */
19     func remove(_ val: Int) -> Bool {
20         if let preIndex = dic[val]{
21             let lastIndex = arr.count - 1
22             dic[val] = nil
23             if lastIndex != preIndex {
24                 dic[arr[lastIndex]] = preIndex
25                 arr.swapAt(preIndex, lastIndex)
26             }
27             arr.removeLast()
28         }else{
29             return false
30         }
31         return true
32         
33     }
34     
35     /** Get a random element from the set. */
36     func getRandom() -> Int {
37         let i = Int.random(in: 0 ..< arr.count)
38         return arr[i]
39     }
40 }
41 
42 /**
43  * Your RandomizedSet object will be instantiated and called as such:
44  * let obj = RandomizedSet()
45  * let ret_1: Bool = obj.insert(val)
46  * let ret_2: Bool = obj.remove(val)
47  * let ret_3: Int = obj.getRandom()
48  */

264ms

 1 class RandomizedSet {
 2     var nums:[Int] = [Int]()
 3     var m:[Int:Int] = [Int:Int]()
 4 
 5     /** Initialize your data structure here. */
 6     init() {
 7         
 8     }
 9     
10     /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
11     func insert(_ val: Int) -> Bool {
12         if m[val] != nil
13         {
14             return false
15         }
16         nums.append(val)
17         m[val] = nums.count - 1
18         return true
19     }
20     
21     /** Removes a value from the set. Returns true if the set contained the specified element. */
22     func remove(_ val: Int) -> Bool {
23         if m[val] == nil
24         {
25             return false
26         }
27         var last = nums.last!
28         m[last] = m[val]
29         nums[m[val]!] = last                
30         nums.removeLast()
31         m[val] = nil
32         return true      
33     }
34     
35     /** Get a random element from the set. */
36     func getRandom() -> Int {
37         return nums[Int.random(in: 0..<nums.count)]      
38     }
39 }
40 
41 /**
42  * Your RandomizedSet object will be instantiated and called as such:
43  * let obj = RandomizedSet()
44  * let ret_1: Bool = obj.insert(val)
45  * let ret_2: Bool = obj.remove(val)
46  * let ret_3: Int = obj.getRandom()
47  */
48  

312ms

 1 class RandomizedSet {
 2     private var dict: [Int: Int]
 3     private var array: [Int]
 4 
 5     /** Initialize your data structure here. */
 6     init() {
 7         self.dict = [Int: Int]()
 8         self.array = [Int]()
 9     }
10 
11     /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
12     func insert(_ val: Int) -> Bool {
13         if let _ = dict[val] {
14             return false
15         } else {
16             dict[val] = array.count
17             array.append(val)
18             return true
19         }
20     }
21 
22     /** Removes a value from the set. Returns true if the set contained the specified element. */
23     func remove(_ val: Int) -> Bool {
24         if let index = dict[val] {
25             if index == array.count - 1 {
26                 array.removeLast()
27             } else {
28                 let last = array.removeLast()
29                 array[index] = last
30                 dict[last] = index
31             }
32             dict[val] = nil
33             return true
34         } else {
35             return false
36         }
37     }
38 
39     /** Get a random element from the set. */
40     func getRandom() -> Int {
41         return array.count == 0 ? -1 : array[Int.random(in: 0..<array.count)]
42     }
43 }
44 
45 /**
46  * Your RandomizedSet object will be instantiated and called as such:
47  * let obj = RandomizedSet()
48  * let ret_1: Bool = obj.insert(val)
49  * let ret_2: Bool = obj.remove(val)
50  * let ret_3: Int = obj.getRandom()
51  */

 

posted @ 2019-01-17 10:53  为敢技术  阅读(296)  评论(0编辑  收藏  举报