栈和队列

232.用栈实现队列

使用栈实现队列的下列操作:

push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。

示例:

1
2
3
4
5
6
7
MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false

leetcode原题地址

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

class MyQueue {
private Stack<Integer> in;
private Stack<Integer> out;
/**
* Initialize your data structure here.
*/
public MyQueue() {
in=new Stack<>();
out=new Stack<>();
}

/**
* Push element x to the back of queue.
*/
public void push(int x) {
in.push(x);
}

/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
if(out.isEmpty()){
while (!in.isEmpty()){
out.push(in.pop());
}
}
return out.pop();
}

/**
* Get the front element.
*/
public int peek() {
if(out.isEmpty()){
while (!in.isEmpty()){
out.push(in.pop());
}
}
return out.peek();
}

/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return in.isEmpty()&&out.isEmpty();
}

}

225. 用队列实现栈

使用队列实现栈的下列操作:

push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空

注意:

你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

leetcode原题地址

解法

在将一个元素 x 插入队列时,为了维护原来的后进先出顺序,需要让 x 插入队列首部。而队列的默认插入顺序是队列
尾部,因此在将 x 插入队列尾部之后,需要让除了 x 之外的所有元素出队列,再入队列。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class MyStack {

Queue<Integer> queue;

/** Initialize your data structure here. */
public MyStack() {
queue=new LinkedList<Integer>();
}

/** Push element x onto stack. */
public void push(int x) {

queue.add(x);
int size = queue.size();
for(int i=0;i<size-1;i++ ){
queue.add(queue.poll());
}

}

/** Removes the element on top of the stack and returns that element. */
public int pop() {

return queue.poll();
}

/** Get the top element. */
public int top() {

return queue.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {

return queue.isEmpty();
}
}

155. 最小栈

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。

示例:

1
2
3
4
5
6
7
8
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.

leetcode原题地址

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
private int min;

/** initialize your data structure here. */
public MinStack() {
stack=new Stack<>();
minStack=new Stack<>();
min=Integer.MAX_VALUE;
}

public void push(int x) {
stack.push(x);
min=Math.min(min,x);
minStack.push(min);
}

public void pop() {
minStack.pop();
stack.pop();
min=minStack.isEmpty()?Integer.MAX_VALUE:minStack.peek();
}

public int top() {
return stack.peek();
}

public int getMin() {
return minStack.peek();
}
}

20. 有效的括号

给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

leetcode原题地址

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public boolean isValid(String s) {

Stack<Character> stack=new Stack<>();
final char[] chars = s.toCharArray();
for(int i=0;i<chars.length;i++){
char ch=chars[i];
if(ch=='('||ch=='{'||ch=='['){
stack.push(ch);
}else {
if(stack.isEmpty()){
return false;
}
char cStack = stack.pop();
boolean b1 = ch == ')' && cStack != '(';
boolean b2 = ch == ']' && cStack != '[';
boolean b3 = ch == '}' && cStack != '{';
if (b1 || b2 || b3) {
return false;
}
}
}
return stack.isEmpty();
}

739. 每日温度

根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。

leetcode原题地址

解法

在遍历数组时用栈把数组中的数存起来,如果当前遍历的数比栈顶元素来的大,说明栈顶元素的下一个比它大的数就是当前元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public int[] dailyTemperatures(int[] arr) {
Stack<Integer> indexs=new Stack<>();

int[] result=new int[arr.length];
for(int i=0;i<arr.length;i++){
while (!indexs.isEmpty()&&arr[i]>arr[indexs.peek()]){
int preIndex=indexs.pop();
result[preIndex]=i-preIndex;

}
indexs.push(i);
}
return result;


}

503. 下一个更大的元素Ⅱ

给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。

示例 1:

1
2
3
4
5
输入: [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数;
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。

注意: 输入数组的长度不会超过 10000。

leetcode原题地址

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int[] nextGreaterElements(int[] nums) {
int[] result=new int[nums.length];
Arrays.fill(result,-1);
Stack<Integer> stack=new Stack();
for(int i=0;i<nums.length*2;i++){
int num=nums[i%nums.length];
while (!stack.isEmpty()&&num>nums[stack.peek()]){
result[stack.pop()]=num;
}
if (i<nums.length){
stack.push(i);
}
}

return result;

}