1.用栈实现队列(简单)
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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> s1;
Stack<Integer> s2;
public MyQueue() {
this.s1=new Stack<Integer>();
this.s2=new Stack<Integer>();
}
public void push(int x) {
s1.push(x);
}
public int pop() {
if(!s2.isEmpty())return s2.pop();
if(s1.isEmpty())return -1;
while(!s1.isEmpty()){
s2.push(s1.pop());
}
return s2.pop();
}
public int peek() {
if(!s2.isEmpty())return s2.peek();
if(s1.isEmpty())return -1;
while(!s1.isEmpty()){
s2.push(s1.pop());
}
return s2.peek();
}
public boolean empty() {
if(s2.isEmpty()&&s1.isEmpty())return true;
return false;
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
2.用队列实现栈(简单)
请你仅使用两个队列实现一个后入先出(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> q1;
Queue<Integer> q2;
public MyStack() {
this.q1=new LinkedList<Integer>();
this.q2=new LinkedList<Integer>();
}
public void push(int x) {
q2.offer(x);
while(!q1.isEmpty()){
q2.offer(q1.poll());
}
Queue<Integer> q;
q=q1;
q1=q2;
q2=q;
}
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
3.有效的括号(简单)
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()" 输出:true 示例 2:
输入:s = "()[]{}" 输出:true 示例 3:
输入:s = "(]" 输出:false 示例 4:
输入:s = "([)]" 输出:false 示例 5:
输入:s = "{[]}" 输出:true
自己模拟思路代码如下:
class Solution {
public boolean isValid(String sh) {
if(sh.length()%2!=0)return false;//如果不是偶数对就false
Stack<Character> s=new Stack<>();
char[] c=sh.toCharArray();
for(char ch:c){
if(ch=='('||ch=='{'||ch=='[')s.push(ch);//前一半就push
else if( ch==')'){//后一半的话先看是否为空,再看是否相同,相同继续,不同或空false
if(!s.isEmpty()&&s.pop()=='(')continue;
else return false;
}
else if( ch=='}'){
if(!s.isEmpty()&&s.pop()=='{')continue;
else return false;
}
else if( ch==']'){
if(!s.isEmpty()&&s.pop()=='[')continue;
else return false;
}
}
return s.isEmpty();//防止剩余多个未匹配的
}
}
评论中的其他思路,代码减少一半:
class Solution {
public boolean isValid(String sh) {
if(sh.length()%2!=0)return false;
Stack<Character> s=new Stack<>();
char[] c=sh.toCharArray();
for(char ch:c){
if(ch=='(')s.push(')');//push对应的一半
else if(ch=='{')s.push('}');
else if(ch=='[')s.push(']');
else if(s.isEmpty()||s.pop()!=ch)return false;//先避免栈空错误,如果pop不同于当前值,说明上一个不是前一半或者没有上一半
}
return s.isEmpty();//防止剩余多个未匹配的
}
}
4.删除字符串中的所有相邻重复项(简单)
给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
示例:
输入:"abbaca" 输出:"ca" 解释: 例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
class Solution {
public String removeDuplicates(String sh) {
Stack<Character> s=new Stack<>();
for(int i=sh.length()-1;i>=0;i--){//栈先入后出,所以倒着遍历
char c=sh.charAt(i);
if(!s.isEmpty()&&s.peek()==c)s.pop();//非空时判断上一个是否相同,相同删除
else s.push(c);
}
String res="";
while(!s.isEmpty()){
res+=s.pop();
}
return res;
}
}
//节省内存,用字符串作为栈
class Solution {
public String removeDuplicates(String s) {
StringBuffer sb=new StringBuffer();
int top=-1;//0为起点,有值时从0开始
char[] arr=s.toCharArray();
for(char c:arr){
if(top>=0&&sb.charAt(top)==c){
sb.deleteCharAt(top);
--top;
}else{
sb.append(c);
++top;
}
}
return sb.toString();
}
}
5.波兰表达式求值(简单)
根据 逆波兰表示法,求表达式的值。
有效的算符包括 +、-、*、/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
注意 两个整数之间的除法只保留整数部分。
可以保证给定的逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入:tokens = ["2","1","+","3","*"] 输出:9 解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9 示例 2:
输入:tokens = ["4","13","5","/","+"] 输出:6 解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6 示例 3:
输入:tokens = ["10","6","9","3","+","-11","","/","","17","+","5","+"] 输出:22 解释:该算式转化为常见的中缀算术表达式为: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22
//ccf类似题,遇到运算符就弹出上两个计算
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> s=new Stack<>();
for(String c:tokens){
if(c.equals("+")||c.equals("*")||c.equals("/")||c.equals("-")){
int a=s.pop();
int b=s.pop();
switch(c){
case "+":{
s.push(a+b);
break;
}
case "-":{
s.push(b-a);
break;
}
case "*":{
s.push(a*b);
break;
}
case "/":{
s.push(b/a);
break;
}
default:
}
}else s.push(Integer.parseInt(c));
}
return s.pop();
}
}
6.滑动窗口最大值(困难)
给你一个整数数组 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 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 示例 2:
输入:nums = [1], k = 1 输出:[1]
//按题目模拟,有个最长用例会超时
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int[] res = new int[nums.length-k+1];
int i=0,j=k-1,count=0;
while(j<nums.length){
int max=nums[i];
for(int h=i;h<=j;h++){
if(nums[h]>max)max=nums[h];
}
res[count++]=max;
j++;
i++;
}
return res;
}
}
//优先队列(大根堆)
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int[] res = new int[nums.length-k+1];
//大根堆初始化:先比较元素,再比较索引
PriorityQueue<int[]> p=new PriorityQueue<>((p1,p2)->p1[0]!=p2[0]?p2[0]-p1[0]:p2[1]-p1[1]);
//先存储一个窗口内容
for(int i=0;i<k;i++){
p.offer(new int[]{nums[i],i});
}
res[0]=p.peek()[0];//存储第一个窗口的最大值
//滑动窗口
for(int i=k;i<=nums.length-1;i++){
p.offer(new int[]{nums[i],i});//每次向右扩展一个元素
while(p.peek()[1]<=i-k)p.poll();//判断最大值是否还在窗口中,不在就删除,可能多个最大值不在窗口,所以while
res[i-k+1]=p.peek()[0];//存储到res中
}
return res;
}
}
//单调队列(双端队列)
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int n= nums.length;
int[] res=new int[n-k+1];
Deque<Integer> d=new ArrayDeque<>();//单调队列初始化,存储索引
for(int i=0;i<k;i++){
while(!d.isEmpty()&&nums[i]>=nums[d.peekLast()])d.pollLast();//非空防止判空,判断目前的是否需要入队,入队不单调则开始出队
d.offerLast(i);//然后再入
}
res[0]=nums[d.peekFirst()];//单调递减,第一个最大
for(int i=k;i<n;i++){
while(!d.isEmpty()&&nums[i]>=nums[d.peekLast()])d.pollLast();//判断入队情况
d.offerLast(i);//出队后入队
while(d.peekFirst()<=i-k)d.pollFirst();//判断第一个值是否还在窗口内
res[i-k+1]=nums[d.peekFirst()];//填最大值
}
return res;
}
}
7.前 K 个高频元素(中等)
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2] 示例 2:
输入: nums = [1], k = 1 输出: [1]
优先队列(PriorityQueue)
堆:用数组实现,多用于移除操作:移除最大值,即移除根节点(先把最大或者最小的移除)。
优先队列初始化,每个元素以数组形式存储
left<right:大顶堆,left>right:小顶堆
小根堆(默认)
PriorityQueue<new int[]> p=new PriorityQueue<>();
PriorityQueue<new int[]> p=new PriorityQueue<>((p1,p2)->p1-p2);
大根堆,先比较值,再比较索引
PriorityQueue<new int[]> p=new PriorityQueue<>((p1,p2)->p2-p1);
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> map=new TreeMap<Integer,Integer>();
for(int num:nums){
map.put(num,map.getOrDefault(num,0)+1);//计数
}
int[] res=new int[k];
PriorityQueue<Map.Entry<Integer,Integer>> p=new PriorityQueue<>((o1,o2)->o1.getValue()-o2.getValue());//对value建立小顶堆
for(Map.Entry<Integer,Integer> n:map.entrySet()){//遍历map
p.offer(n);
if(p.size()>k)p.poll();//如果小根堆数量比k大,就poll,堆会把顶端的poll掉,所以会先把数量最少的排出
}
for(int i=k-1;i>=0;i--){
res[i]=p.poll().getKey();//从数量最多的开始
}
return res;
}
}
链接:https://leetcode-cn.com
来源:力扣(LeetCode)