File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Initialize your data structure here.
3
+ */
4
+ const AllOne = function ( ) {
5
+ this . map = new Map ( )
6
+ }
7
+
8
+ /**
9
+ * Inserts a new key <Key> with value 1. Or increments an existing key by 1.
10
+ * @param {string } key
11
+ * @return {void }
12
+ */
13
+ AllOne . prototype . inc = function ( key ) {
14
+ let curCount
15
+ if ( this . map . has ( key ) ) {
16
+ curCount = this . map . get ( key ) + 1
17
+ } else {
18
+ curCount = 1
19
+ }
20
+ this . map . set ( key , curCount )
21
+ }
22
+
23
+ /**
24
+ * Decrements an existing key by 1. If Key's value is 1, remove it from the data structure.
25
+ * @param {string } key
26
+ * @return {void }
27
+ */
28
+ AllOne . prototype . dec = function ( key ) {
29
+ if ( this . map . has ( key ) ) {
30
+ if ( this . map . get ( key ) > 1 ) {
31
+ this . map . set ( key , this . map . get ( key ) - 1 )
32
+ } else this . map . delete ( key )
33
+ } else {
34
+ return
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Returns one of the keys with maximal value.
40
+ * @return {string }
41
+ */
42
+ AllOne . prototype . getMaxKey = function ( ) {
43
+ let max = - Infinity ,
44
+ maxStr = ''
45
+ for ( let k of this . map ) {
46
+ if ( k [ 1 ] > max ) {
47
+ max = k [ 1 ]
48
+ maxStr = k [ 0 ]
49
+ }
50
+ }
51
+ return maxStr
52
+ }
53
+
54
+ /**
55
+ * Returns one of the keys with Minimal value.
56
+ * @return {string }
57
+ */
58
+ AllOne . prototype . getMinKey = function ( ) {
59
+ let min = Infinity ,
60
+ minStr = ''
61
+ for ( let k of this . map ) {
62
+ if ( k [ 1 ] < min ) {
63
+ min = k [ 1 ]
64
+ minStr = k [ 0 ]
65
+ }
66
+ }
67
+ return minStr
68
+ }
69
+
70
+ /**
71
+ * Your AllOne object will be instantiated and called as such:
72
+ * var obj = Object.create(AllOne).createNew()
73
+ * obj.inc(key)
74
+ * obj.dec(key)
75
+ * var param_3 = obj.getMaxKey()
76
+ * var param_4 = obj.getMinKey()
77
+ */
You can’t perform that action at this time.
0 commit comments