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

Commit4c640c0

Browse files
add a solution for 155
1 parent7a7e795 commit4c640c0

File tree

1 file changed

+43
-23
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+43
-23
lines changed

‎src/main/java/com/fishercoder/solutions/_155.java

Lines changed: 43 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,16 @@
11
packagecom.fishercoder.solutions;
22

3+
importjava.util.Deque;
4+
importjava.util.LinkedList;
35
importjava.util.Stack;
46

5-
/**
6-
* 155. Min Stack
7-
* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
8-
9-
* push(x) -- Push element x onto stack.
10-
* pop() -- Removes the element on top of the stack.
11-
* top() -- Get the top element.
12-
* getMin() -- Retrieve the minimum element in the stack.
13-
14-
* Example:
15-
* MinStack minStack = new MinStack();
16-
* minStack.push(-2);
17-
* minStack.push(0);
18-
* minStack.push(-3);
19-
* minStack.getMin(); --> Returns -3.
20-
* minStack.pop();
21-
* minStack.top(); --> Returns 0.
22-
* minStack.getMin(); --> Returns -2.
23-
*/
24-
257
publicclass_155 {
268

279
publicstaticclassSolution1 {
2810
classMinStack {
2911
privateStack<Integer>stack;
3012
privateintmin;
3113

32-
/**
33-
* initialize your data structure here.
34-
*/
3514
publicMinStack() {
3615
stack =newStack();
3716
min =Integer.MAX_VALUE;
@@ -64,4 +43,45 @@ public int getMin() {
6443
}
6544
}
6645
}
46+
47+
publicstaticclassSolution2 {
48+
/**
49+
* We could store a pair onto the stack: the first element in the pair is the value itself,
50+
* the second element in the pair is the current minimum element so far seen on the stack.
51+
*/
52+
classMinStack {
53+
Deque<int[]>stack;
54+
55+
publicMinStack() {
56+
stack =newLinkedList<>();
57+
}
58+
59+
publicvoidpush(intval) {
60+
if (!stack.isEmpty()) {
61+
int[]last =stack.peekLast();
62+
intcurrentMin =last[1];
63+
if (val <currentMin) {
64+
stack.addLast(newint[]{val,val});
65+
}else {
66+
stack.addLast(newint[]{val,currentMin});
67+
}
68+
}else {
69+
stack.addLast(newint[]{val,val});
70+
}
71+
}
72+
73+
publicvoidpop() {
74+
stack.pollLast();
75+
}
76+
77+
publicinttop() {
78+
returnstack.peekLast()[0];
79+
}
80+
81+
publicintgetMin() {
82+
returnstack.peekLast()[1];
83+
}
84+
}
85+
86+
}
6787
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp