-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
380 Insert Delete GetRandom O(1).swift
69 lines (59 loc) 路 1.82 KB
/
380 Insert Delete GetRandom O(1).swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
// 380 Insert Delete GetRandom O(1).swift
// LeetCode-Solutions
//
// Created by Aleksandar Dinic on 12/06/2020.
// Copyright 漏 2020 Aleksandar Dinic. All rights reserved.
//
import Foundation
/// Source: https://leetcode.com/problems/insert-delete-getrandom-o1/
class RandomizedSet {
private var arr: [Int]
private var dict: [Int: Int]
/// Initialize data structure.
init() {
arr = [Int]()
dict = [Int: Int]()
}
/// Inserts a value to the set.
///
/// - Parameter val: The value.
/// - Returns: True if the set did not already contain the specified element, otherwise
/// returns false.
///
/// - Complexity:
/// - time: O(1), only constant time is used.
/// - space: O(1), only constant space is used.
func insert(_ val: Int) -> Bool {
guard dict[val] == nil else { return false }
arr.append(val)
dict[val] = arr.count - 1
return true
}
/// Removes a value from the set.
///
/// - Parameter val: The value
/// - Returns: True if the set contained the specified element, otherwise returns false.
///
/// - Complexity:
/// - time: O(1), only constant time is used.
/// - space: O(1), only constant space is used.
func remove(_ val: Int) -> Bool {
guard let indexToRemove = dict[val], let last = arr.last else { return false }
arr[indexToRemove] = last
arr.removeLast()
dict[last] = indexToRemove
dict[val] = nil
return true
}
/// Get a random element from the set.
///
/// - Returns: Random element.
///
/// - Complexity:
/// - time: O(1), only constant time is used.
/// - space: O(1), only constant space is used.
func getRandom() -> Int {
return arr[Int.random(in: 0..<arr.count)]
}
}