Skip to content

Commit 7923726

Browse files
authored
Create 432-all-oone-data-structure.js
1 parent 1483f83 commit 7923726

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

432-all-oone-data-structure.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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+
*/

0 commit comments

Comments
 (0)