Last active
September 25, 2016 05:57
-
-
Save Shuumatsu/ae0b6bb1f968a1cd7a2b88c36ac9090e to your computer and use it in GitHub Desktop.
a stack that supports getMin() in O(1) time and O(1) extra space
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class MinStack { | |
stack: number[] = []; | |
num: number = 0; | |
private _min: number; | |
get min(): number { | |
if (this.num > 0) { | |
return this._min; | |
} | |
} | |
push(el: number) { | |
this.num++; | |
if (this.num === 1) { | |
this.stack.push(el); | |
this._min = el; | |
return; | |
} | |
if (el >= this.min) { | |
this.stack.push(el); | |
return; | |
} | |
this.stack.push(2 * el - this.min); | |
this._min = el; | |
} | |
pop(): number { | |
if (this.num === 0) { | |
return; | |
} | |
this.num--; | |
let el = this.stack.pop(); | |
let pop = el; | |
if (el < this.min) { | |
pop = this.min; | |
this._min = 2 * this.min - el; | |
} | |
return pop; | |
} | |
} | |
// max version | |
class MaxStack { | |
stack: number[] = []; | |
num: number = 0; | |
private _max: number; | |
get max(): number { | |
if (this.num > 0) { | |
return this._max; | |
} | |
} | |
push(el: number) { | |
this.num++; | |
if (this.num === 1) { | |
this.stack.push(el); | |
this._max = el; | |
return; | |
} | |
if (el <= this.max) { | |
this.stack.push(el); | |
return; | |
} | |
this.stack.push(2 * el - this.max); | |
this._max = el; | |
} | |
pop(): number { | |
if (this.num === 0) { | |
return; | |
} | |
this.num--; | |
let el = this.stack.pop(); | |
let pop = el; | |
if (el > this.max) { | |
pop = this.max; | |
this._max = 2 * this.max - el; | |
} | |
return pop; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
idea comes from http://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/