-
Notifications
You must be signed in to change notification settings - Fork 0
/
380.o-1-时间插入、删除和获取随机元素.js
99 lines (83 loc) · 2.27 KB
/
380.o-1-时间插入、删除和获取随机元素.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* @lc app=leetcode.cn id=380 lang=javascript
*
* [380] O(1) 时间插入、删除和获取随机元素
*/
// @lc code=start
var RandomizedSet = function() {
// initialize and map and arr
this.valToIndexMap = new Map()
this.arr = new Array()
}
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {
// check if the value exists, if exist, return false
if (this.valToIndexMap.has(val)) {
return false
}
// add val to tail
this.arr.push(val)
// record index
this.valToIndexMap.set(val, this.arr.length - 1)
// return true
return true
}
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {
// if val is not existed, return false
if (!this.valToIndexMap.has(val)) {
return false
}
// find the value and index at tail
let tailIndex = this.arr.length - 1
let tailVal = this.arr[tailIndex]
// find indexToRemove of val
let indexToRemove = this.valToIndexMap.get(val)
// update valToIndexMap
// 1. update valueAtDetail's index to indexToRemove
this.valToIndexMap.set(tailVal, indexToRemove)
// 2. delete val(not index) at valToIndexMap
this.valToIndexMap.delete(val)
// swap current val with the val at tail
swap(this.arr, indexToRemove, tailIndex)
// pop tail val
this.arr.pop()
// return true
return true
function swap(arr, i, j) {
let temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
/**
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {
// use random function to update
return this.arr[Math.floor(Math.random() * this.arr.length)]
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* var obj = new RandomizedSet()
* var param_1 = obj.insert(val)
* var param_2 = obj.remove(val)
* var param_3 = obj.getRandom()
*/
// @lc code=end
// const randomSet = new RandomizedSet()
// console.log(randomSet.insert(1)) // true
// console.log(randomSet.insert(2)) // true
// console.log(randomSet.insert(3)) // true
// console.log(randomSet.insert(2)) // false
// console.log(randomSet.remove(2)) // true
// console.log('randomSet.arr', randomSet.arr) // [1,3]
// console.log(randomSet.remove(2)) // false
// console.log(randomSet.getRandom()) // any
module.exports = { RandomizedSet }