前言
先对栈和队列有个再次熟悉的过程,掌握栈与队列的操作方法。其次就是双向队列,优先队列的使用。
问题分析
232题与225题是栈与队列的互相实现,主要是学习这两个涉及的操作方法。
232题:
class MyQueue {//两个栈来模拟进出队列
Stack<Integer> stack_in;
Stack<Integer> stack_out;
public MyQueue() {
stack_in = new Stack<>();
stack_out = new Stack<>();
}
public void swap(){
if(!stack_out.isEmpty()) return;
while(!stack_in.isEmpty()) stack_out.push(stack_in.pop());
}
public void push(int x) {
stack_in.push(x);
}
public int pop() {
swap();
return stack_out.pop();
}
public int peek() {
swap();
return stack_out.peek();
}
public boolean empty() {
return stack_in.isEmpty() && stack_out.isEmpty();
}
}
225题:
class MyStack {
Queue<Integer> que1;
Queue<Integer> que2;
public MyStack() {
que1 = new LinkedList<>();
que2 = new LinkedList<>();
}
public void push(int x) {
que2.offer(x);//暂时存放
while(!que1.isEmpty()){//que1不为空,把que1元素再出来放进que2中;经过下一步的que1和2的交换,que1变成栈的顺序
que2.offer(que1.poll());
}
Queue<Integer> temp = que1;//que1为空的时候,就把que2的元素放进que1中
que1 = que2;
que2 = temp;
}
public int pop() {
return que1.poll();
}
public int top() {//get元素
return que1.peek();
}
public boolean empty() {
return que1.isEmpty();
}
}
20题,有效的括号,典型的栈处理问题。
class Solution {
public boolean isValid(String s) {//双向队列Deque,分三种情况:左括号多,右括号多,不多但是括号不匹配。
Deque<Character> stack = new LinkedList<>();
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())//空栈说明右括弧多,
// 后面那个是说不多但是括号不匹配,注意不是pop移除,而是peek只获取值来比较
return false;
else
stack.pop();
}
return stack.isEmpty();//返回false,左括弧多,因为栈没有空
}
}
1047题也是匹配问题
class Solution {
public String removeDuplicates(String s) {//拿字符串直接当栈,按照栈的原理进行匹配和删除
StringBuffer sc = new StringBuffer();//构造的栈
int top = -1;//代表栈sc的长度
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(top >= 0 && ch == sc.charAt(top)){//sc.charAt(top)相当于当前值跟前一个值比较
sc.deleteCharAt(top);
top--;
}
else{
sc.append(ch);
top++;
}
}
return sc.toString();
}
}
150题,也是匹配问题
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new LinkedList<>();
for(int i = 0; i < tokens.length; i++){
if("+".equals(tokens[i])) {//equals判断对象值是否相等
stack.push(stack.pop() + stack.pop());
}
else if("-".equals(tokens[i])) {
stack.push(-stack.pop() + stack.pop());//减号特殊处理可以理解
}
else if("*".equals(tokens[i])) {
stack.push(stack.pop() * stack.pop());
}
else if("/".equals(tokens[i])) {
int temp1 = stack.pop();
int temp2 = stack.pop();
stack.push(temp2 / temp1);//除法这,pop()出的两个数,有除数和被除数,所以要分清楚
}
else {
stack.push(Integer.valueOf(tokens[i]));
}
}
return stack.pop();
}
}
239题是个hard,确实难啊。
直接粘一下相关想法:
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {//双向队列,左右皆可增减
Deque<Integer> que = new LinkedList<>();
int res[] = new int[nums.length - k + 1];
for(int i = 0;i < k; i++){
while(!que.isEmpty() && nums[i] > que.peekLast())
que.removeLast();//小于就出队
que.offerLast(nums[i]);//添加到队尾
}
int count = 0;
res[0] = que.peekFirst();//第一个值有了,前面对第一个滑动窗口选出了一个最大值
count++;
for(int j = k; j < nums.length; j++){
if(nums[j - k] == que.peekFirst()) que.removeFirst();//排除[1,-1],k=1,输出为[1,-1]的时候,
//相当于一个滑动窗口结束,队头(最大值)的时代结束,滑动窗口移动之后,滑动窗口不含该值了,
// 就从队列中把这个最大值去除,等待新的滑动窗口中的最大值
while(!que.isEmpty() && nums[j] > que.peekLast())
que.removeLast();//把队列中小于nums[j]的都出队,保证队头最大值
que.offerLast(nums[j]);
res[count] = que.peekFirst();
count++;
}
return res;
}
}
347题,
考虑思路:三个步骤
最后的输出是无序就可以,所以不需要数组再反转。
class Solution {
public int[] topKFrequent(int[] nums, int k) {//top-k,大顶堆,小顶堆
Map<Integer, Integer> map = new HashMap<>();//存放每个值出现的频率
for(int i = 0; i < nums.length; i++){
map.put(nums[i],map.getOrDefault(nums[i], 0) + 1);
}
//计算完出现的频率之后,开始排序
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>(){
public int compare(Integer c1, Integer c2){
return map.get(c1) - map.get(c2);//PriorityQueue中默认小顶堆,
// 但排序排的是key,我们这用value,所以重写coparator
//要是用大顶堆,就是map.get(c2)-map.get(c1);;;小顶堆:o1 < o2 ? -1 : 1;
}
});//用来存放前k个最大值
for(Integer key: map.keySet()){
if(pq.size() < k)
pq.add(key);
else if(map.get(key) > map.get(pq.peek())){
pq.remove();
pq.add(key);
}
}
//将排好序的小顶堆的k个值转化为list输出
int res[] = new int[k];
int count = 0;
while(!pq.isEmpty()){
res[count] = pq.poll();//remove也是可以!
count++;
}
return res;
}
}
!!!把想说的都写在注释里,这样看起来也不会忘。像这样一章节,要是等着最后再整理,肯定会忘记一些关键的,这样就不会了。