Last active
March 5, 2017 13:21
-
-
Save vitkarpov/edef7ad127e3224c146f26d1cfb86ff3 to your computer and use it in GitHub Desktop.
"Cracking the coding interview", Stacks and Queues, 3.2
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
/** | |
* Стек, который реализует метод min, | |
* кроме стандартный push и pop | |
* | |
* @example | |
* const s = new Stack(); | |
* s.push(5); | |
* // 5 | |
* console.log(s.min()); | |
* s.push(6); | |
* s.push(3); | |
* // 3 | |
* console.log(s.min()); | |
* s.push(7); | |
* s.pop(); | |
* s.pop(); | |
* // 5 | |
* console.log(s.min()); | |
*/ | |
class Stack { | |
constructor() { | |
this._s1 = []; | |
this._s2 = []; | |
} | |
push(value) { | |
if (value <= this.min()) { | |
this._s2.push(value); | |
} | |
this._s1.push(value); | |
} | |
pop() { | |
const value = this._s1.pop(); | |
if (value === this.min()) { | |
this._s2.pop(); | |
} | |
return value; | |
} | |
min() { | |
if (this._s2.length === 0) { | |
return Number.MAX_SAFE_INTEGER; | |
} | |
return this._s2[this._s2.length - 1]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment