232. 用栈实现队列
题目
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
):
实现 MyQueue
类:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
说明:
- 你 只能 使用标准的栈操作 —— 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例 1:
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
答案
class MyQueue {Stack<Integer> stackIn;Stack<Integer> stackOut;public MyQueue() {stackIn = new Stack();stackOut = new Stack();}public void push(int x) {stackIn.push(x);}public int pop() {deal();return stackOut.pop();}public int peek() {deal();return stackOut.peek();}public boolean empty() {return stackIn.isEmpty() && stackOut.isEmpty();}void deal(){if(!stackOut.isEmpty()){return;}while(!stackIn.isEmpty()){stackOut.push(stackIn.pop());}}
}
225. 用队列实现栈
题目
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push
、top
、pop
和 empty
)。
实现 MyStack
类:
void push(int x)
将元素 x 压入栈顶。int pop()
移除并返回栈顶元素。int top()
返回栈顶元素。boolean empty()
如果栈是空的,返回true
;否则,返回false
。
注意:
- 你只能使用队列的标准操作 —— 也就是
push to back
、peek/pop from front
、size
和is empty
这些操作。 - 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例:
输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
答案
class MyStack {Queue<Integer> queue1;Queue<Integer> queue2;public MyStack() {queue1 = new LinkedList();queue2 = new LinkedList();}public void push(int x) {queue2.offer(x);while(!queue1.isEmpty()){queue2.offer(queue1.poll());}Queue<Integer> temp = queue1;queue1 = queue2;queue2 = temp;}public int pop() {return queue1.poll();}public int top() {return queue1.peek();}public boolean empty() {return queue1.isEmpty();}
}
20. 有效的括号
题目
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
答案
class Solution {public boolean isValid(String s) {Stack<Character> stack = new Stack();for(int i=0;i<s.length();i++){char ch = s.charAt(i);if(ch=='{'){stack.push('}');}else if(ch=='['){stack.push(']');}else if(ch=='('){stack.push(')');}else if(stack.isEmpty() || ch!=stack.peek()){return false;}else{stack.pop();}} return stack.isEmpty();}
}
1047. 删除字符串中的所有相邻重复项
题目
给出由小写字母组成的字符串 S
,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
示例:
输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
答案
class Solution {public String removeDuplicates(String s) {Stack<Character> stack = new Stack();for(int i=0;i<s.length();i++){//当栈char ch = s.charAt(i);if(stack.isEmpty() || stack.peek()!=ch){stack.push(ch);}else{stack.pop();}}String res = "";while(!stack.isEmpty()){res = stack.pop() + res;}return res;}
}
150. 逆波兰表达式求值
题目
给你一个字符串数组 tokens
,表示一个根据 逆波兰表示法 表示的算术表达式。
请你计算该表达式。返回一个表示表达式值的整数。
注意:
- 有效的算符为
'+'
、'-'
、'*'
和'/'
。 - 每个操作数(运算对象)都可以是一个整数或者另一个表达式。
- 两个整数之间的除法总是 向零截断 。
- 表达式中不含除零运算。
- 输入是一个根据逆波兰表示法表示的算术表达式。
- 答案及所有中间计算结果可以用 32 位 整数表示。
示例 1:
输入:tokens = ["2","1","+","3","*"]
输出:9
解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
示例 2:
输入:tokens = ["4","13","5","/","+"]
输出:6
解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
答案
class Solution {public int evalRPN(String[] tokens) {Stack<Integer> stack = new Stack();for(String str : tokens){if("+".equals(str)){stack.push(stack.pop()+stack.pop());}else if("-".equals(str)){stack.push(-stack.pop()+stack.pop());}else if("*".equals(str)){stack.push(stack.pop()*stack.pop());}else if("/".equals(str)){int num1 = stack.pop();int num2 = stack.pop();stack.push(num2/num1);}else{stack.push(Integer.parseInt(str));}}return stack.pop();}
}
239. 滑动窗口最大值
题目
给你一个整数数组 nums
,有一个大小为 k
的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k
个数字。滑动窗口每次只向右移动一位。
返回 滑动窗口中的最大值 。
示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 31 [3 -1 -3] 5 3 6 7 31 3 [-1 -3 5] 3 6 7 51 3 -1 [-3 5 3] 6 7 51 3 -1 -3 [5 3 6] 7 61 3 -1 -3 5 [3 6 7] 7
示例 2:
输入:nums = [1], k = 1
输出:[1]
答案
class Solution {public int[] maxSlidingWindow(int[] nums, int k) {int len = nums.length;int[] res = new int[len-k+1];int index = 0;Deque<Integer> queue = new LinkedList();for(int i=0;i<len;i++){while(!queue.isEmpty() && queue.peek()<i-k+1){queue.poll();}while(!queue.isEmpty() && nums[i]>nums[queue.peekLast()]){queue.pollLast();}queue.offer(i);if(i>=k-1){res[index++] = nums[queue.peek()];}} return res;}
}
347. 前 K 个高频元素
题目
给你一个整数数组 nums
和一个整数 k
,请你返回其中出现频率前 k
高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
答案
class Solution {public int[] topKFrequent(int[] nums, int k) {Map<Integer,Integer> map = new HashMap();for(int num : nums){map.put(num,map.getOrDefault(num,0)+1);}PriorityQueue<int[]> queue = new PriorityQueue<>((a,b) -> a[1]-b[1]);//注意< >for(Map.Entry<Integer,Integer> entry : map.entrySet()){int val = entry.getKey();int count = entry.getValue();int[] temp = new int[2];temp[0] = val;temp[1] = count;queue.offer(temp);if(queue.size()>k){queue.poll();}}int[] res = new int[k];for(int i=0;i<k;i++){res[i] = queue.poll()[0];}return res;}
}