150 逆波兰表达式求值
class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
String c = tokens[i];
if (c.equals("+") || c.equals("-") || c.equals("*") || c.equals("/")) {
int second = Integer.parseInt(stack.pop());
int first = Integer.parseInt(stack.pop());
if (c.equals("+")) {
stack.push(String.valueOf(first + second));
}
if (c.equals("-")) {
stack.push(String.valueOf(first - second));
}
if (c.equals("*")) {
stack.push(String.valueOf(first * second));
}
if (c.equals("/")) {
stack.push(String.valueOf(first / second));
}
} else {
stack.push(c);
}
}
return Integer.parseInt(stack.pop());
}
}
239 滑动窗口最大值
本人想到的解法,近乎暴力解,没办法过全部用例,然后由此学习了单调队列
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
Queue<Integer> queue = new LinkedList<>();
int max = Integer.MIN_VALUE;
int[] res = new int[nums.length - k + 1];
int count = 0;
for(int i = 0; i < k; i++) {
queue.offer(nums[i]);
max = Math.max(max, nums[i]);
}
res[count++] = max;
for(int i = k ; i < nums.length; i++) {
queue.offer(nums[i]);
max = Math.max(max, nums[i]);
if (queue.poll() >= max) {
Queue<Integer> temp = new LinkedList<>();
int anotherMax = Integer.MIN_VALUE;
while(!queue.isEmpty()) {
int num = queue.poll();
anotherMax = Math.max(anotherMax, num);
temp.offer(num);
}
max = anotherMax;
while(!temp.isEmpty()) {
queue.offer(temp.poll());
}
}
res[count++] = max;
}
return res;
}
}
// 单调队列写法
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
MonotonicQueue queue = new MonotonicQueue();
int[] res = new int[nums.length - k + 1];
int count = 0;
for(int i = 0; i < k; i++) {
queue.add(nums[i]);
}
res[count++] = queue.max();
for(int i = k ; i < nums.length; i++) {
queue.add(nums[i]);
queue.poll(nums[i - k]);
res[count++] = queue.max();
}
return res;
}
}
class MonotonicQueue {
private LinkedList<Integer> maxQeque = new LinkedList<>();
public void add(int val) {
while(!maxQeque.isEmpty() && maxQeque.getLast() < val) {
maxQeque.pollLast();
}
maxQeque.offer(val);
}
public void poll(int val) {
if(!maxQeque.isEmpty() && maxQeque.peek() == val) {
maxQeque.remove();
}
}
public int max() {
return maxQeque.peek();
}
}
347 前K个高频元素
学习优先级队列:大顶堆(完全二叉树,父节点最大)和小顶堆(完全二叉树,父节点最小)
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
PriorityQueue<int[]> pq = new PriorityQueue<>((Comparator.comparingInt(o -> o[1])));
for(int num: nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
pq.offer(new int[]{entry.getKey(), entry.getValue()});
while(pq.size() > k) {
pq.poll();
}
}
int[] res = new int[k];
int count = 0;
for(int[] in : pq) {
res[count++] = in[0];
}
return res;
}
}