forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDinner Plate Stacks.js
62 lines (56 loc) · 1.31 KB
/
Dinner Plate Stacks.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
/**
* @param {number} capacity
*/
var DinnerPlates = function(capacity) {
this.capacity = capacity;
this.stacks = [];
};
/**
* @param {number} val
* @return {void}
*/
DinnerPlates.prototype.push = function(val) {
var needNewStack = true
for (var i = 0; i < this.stacks.length; i++) {
if (this.stacks[i].length < this.capacity) {
this.stacks[i].push(val);
needNewStack = false;
break;
}
}
if (needNewStack) {
this.stacks.push([val]);
}
};
/**
* @return {number}
*/
DinnerPlates.prototype.pop = function() {
var val = -1;
for (var i = this.stacks.length - 1; i >= 0; i--) {
if (this.stacks[i].length > 0) {
val = this.stacks[i].pop();
break;
}
}
return val;
};
/**
* @param {number} index
* @return {number}
*/
DinnerPlates.prototype.popAtStack = function(index) {
// console.log(index, this.stacks, ...this.stacks[index])
var val = -1;
if (this.stacks[index] && this.stacks[index].length > 0) {
val = this.stacks[index].pop()
}
return val;
};
/**
* Your DinnerPlates object will be instantiated and called as such:
* var obj = new DinnerPlates(capacity)
* obj.push(val)
* var param_2 = obj.pop()
* var param_3 = obj.popAtStack(index)
*/