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

Commitc920110

Browse files
add min stack
1 parent8ef7a24 commitc920110

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

‎EASY/src/easy/MinStack.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
packageeasy;
2+
3+
importjava.util.*;
4+
5+
publicclassMinStack {
6+
7+
privateStack<Integer>stack;
8+
privateintmin;
9+
10+
/** initialize your data structure here. */
11+
publicMinStack() {
12+
stack =newStack();
13+
min =Integer.MAX_VALUE;
14+
}
15+
16+
publicvoidpush(intx) {
17+
/**All the trick happens here, we push the second minimum number onto the stack before we push the newer one,
18+
* this way, when popping, we could always get the next minimum one in constant time.*/
19+
if(x <=min){
20+
stack.push(min);
21+
min =x;
22+
}
23+
stack.push(x);
24+
}
25+
26+
publicvoidpop() {
27+
if(min ==stack.peek()){
28+
stack.pop();
29+
min =stack.pop();
30+
}else {
31+
stack.pop();
32+
}
33+
if(stack.isEmpty())min =Integer.MAX_VALUE;
34+
}
35+
36+
publicinttop() {
37+
returnstack.peek();
38+
}
39+
40+
publicintgetMin() {
41+
returnmin;
42+
}
43+
44+
}

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
|173|[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/)|[Queue](../../blob/master/MEDIUM/src/medium/BSTIterator_using_q.java)[Stack](../../blob/master/MEDIUM/src/medium/BSTIterator_using_stack.java)| O(1)|O(h)| Medium|
2828
|172|[Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/)|[Solution](../../blob/master/EASY/src/easy/FactorialTrailingZeroes.java)| O(logn)|O(1)| Easy
2929
|162|[Find Peak Element](https://leetcode.com/problems/find-peak-element/)|[Solution](../../blob/master/MEDIUM/src/medium/FindPeakElement.java)| O(1)|O(logn)/O(n)| Binary Search|
30+
|155|[Min Stack](https://leetcode.com/problems/min-stack/)|[Solution](../../blob/master/EASY/src/easy/MinStack.java)| O(1)|O(n) | Easy| Stack
3031
|140|[Word Break II](https://leetcode.com/problems/word-break-ii/)|[Solution](../../blob/master/HARD/src/hard/WordBreakII.java)| ? |O(n^2) | Hard| Backtracking/DFS
3132
|139|[Word Break](https://leetcode.com/problems/word-break/)|[Solution](../../blob/master/MEDIUM/src/medium/WordBreak.java)| O(n^2)|O(n) | Medium| DP
3233
|133|[Clone Graph](https://leetcode.com/problems/clone-graph/)|[Solution](../../blob/master/MEDIUM/src/medium/CloneGraph.java)| O(n)|O(n) | Medium| HashMap, BFS

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp