Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit30eff76

Browse files
committed
Added 1 JS solution for problem 155
1 parent737ba0c commit30eff76

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎javascript/155-Min-Stack.js‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
//////////////////////////////////////////////////////////////////////////////
2+
// Two Stacks
3+
// Time: O(1)
4+
// Space: O(n)
5+
// This solution uses two stacks to save the total values and the minimum
6+
// values. Per each new value if it is less than or equal to the current
7+
// minimum it is pushed to both stacks. We save duplicate minimum values to
8+
// avoid the conundrum of inquiring whether the minimum value can be removed
9+
// (i.e. when the minimum value equals the top value can it be removed or are
10+
// there duplicate values in the main stack).
11+
//////////////////////////////////////////////////////////////////////////////
12+
13+
classMinStack{
14+
/**
15+
*@constructor
16+
*/
17+
constructor(){
18+
this.mainStack=[];
19+
this.minStack=[];
20+
}
21+
22+
/**
23+
*@param {number} val
24+
*@return {void}
25+
*/
26+
push(val){
27+
this.mainStack.push(val);
28+
if(!this.minStack.length||val<=this.minStack[this.minStack.length-1]){
29+
this.minStack.push(val);
30+
}
31+
}
32+
33+
/**
34+
*@return {void}
35+
*/
36+
pop(){
37+
constval=this.mainStack.pop();
38+
if(val===this.minStack[this.minStack.length-1]){
39+
this.minStack.pop();
40+
}
41+
}
42+
43+
/**
44+
*@return {number}
45+
*/
46+
top(){
47+
returnthis.mainStack[this.mainStack.length-1];
48+
}
49+
50+
/**
51+
*@return {number}
52+
*/
53+
getMin(){
54+
returnthis.minStack[this.minStack.length-1];
55+
}
56+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp