232. 用栈实现队列
难度:简单
使用栈实现队列的下列操作:
- push(x) – 将一个元素放入队列的尾部。
- pop() – 从队列首部移除元素。
- peek() – 返回队列首部的元素。
- empty() – 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
- 你只能使用标准的栈操作 – 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
- 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
使用两个栈实现队列,一个元素需要经过两个栈才能出队列,在经过第一个栈时元素顺序被反转,经过第二个栈时再次被反转,此时就是先进先出顺序。
class MyQueue {
private Stack<Integer> in = new Stack<>();
private Stack<Integer> out = new Stack<>();
/** Initialize your data structure here. */
public MyQueue() {
}
/** 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() {
in2out();
return out.pop();
}
/** Get the front element. */
public int peek() {
in2out();
return out.peek();
}
private void in2out () {
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
}
/** 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 操作)。
在将一个元素 x 插入队列时,为了维护原来的后进先出顺序,需要让 x 插入队列首部。而队列的默认插入顺序是队列尾部,因此在将 x 插入队列尾部之后,需要让除了 x 之外的所有元素出队列,再入队列。
class MyStack {
private Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue.add(x);
int count = queue.size();
while (count-- > 1) {
queue.add(queue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.remove();
}
/** 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() – 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
使用三个成员变量,一个栈dataStack
用来保存原数据,一个栈minStack
,它的栈顶是最小的元素,一个整数min
用来保存最小值。
class MinStack {
private Stack<Integer> dataStack;
private Stack<Integer> minStack;
private int min;
/**
* initialize your data structure here.
*/
public MinStack () {
dataStack = new Stack<>();
minStack = new Stack<>();
min = Integer.MAX_VALUE;
}
public void push (int x) {
dataStack.add(x);
min = Math.min(min, x);
minStack.add(min);
}
public void pop () {
dataStack.pop();
minStack.pop();
min = minStack.isEmpty() ? Integer.MAX_VALUE : minStack.peek();
}
public int top () {
return dataStack.peek();
}
public int getMin () {
return minStack.peek();
}
}
20. 有效的括号
难度:简单
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
遍历字符串,把每种左括号压入栈,不是左括号的就弹出栈顶元素,用三个 boolean 变量判断是否能和前面对应的左括号匹配。如果遍历完了,就最后看栈是不是正好空了。
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char cPop = stack.pop();
boolean b1 = cPop != '(' && c == ')';
boolean b2 = cPop != '[' && c == ']';
boolean b3 = cPop != '{' && c == '}';
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]
范围内的整数。
遍历数组的同时,把当前元素的索引存放到一个栈内,如果 当前元素的值 大于 栈顶存放的索引对应的数值元素的值,就用当前索引减去栈顶存放的那个索引,放到结果数组内。
public int[] dailyTemperatures(int[] T) {
int n = T.length;
Stack<Integer> index = new Stack<>();
int[] ans = new int[n];
for (int curIndex = 0; curIndex < n; curIndex++) {
while (!index.isEmpty() && T[curIndex] > T[index.peek()]) {
int preIndex = index.pop();
ans[preIndex] = curIndex - preIndex;
}
index.add(curIndex);
}
return ans;
}
503. 下一个更大元素 II
难度:中等
循环数组中比当前元素大的下一个元素
给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。
示例 1:
输入: [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数;
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。
注意: 输入数组的长度不会超过 10000。
将数组遍历两次,模拟循环数组。判断操作和上一题类似,如果当前元素大于栈顶元素,结果数组中的对应位置的元素就是当前元素。
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
Arrays.fill(ans, -1);
Stack<Integer> pre = new Stack<>();
for (int i = 0; i < 2 * n; i++) {
int num = nums[i % n];
while (!pre.isEmpty() && num > nums[pre.peek()]) {
ans[pre.pop()] = num;
}
if (i < n) {
pre.push(i);
}
}
return ans;
}