今日任务:
150. 逆波兰表达式求值
239. 滑动窗口最大值
347.前 K 个高频元素
150. 逆波兰表达式求值
题目链接:. - 力扣(LeetCode)
知识点: 栈解决匹配问题的好手段
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
String ops = "+-*/";
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].length() == 1 && ops.contains(String.valueOf(tokens[i].charAt(0)))){
int op1 = 0, op2 = 0;
if (!stack.isEmpty()) {
op1 = stack.pop();
}
if (!stack.isEmpty()) {
op2 = stack.pop();
}
if (tokens[i].charAt(0) == '+') {
stack.push(op2 + op1);
}
if (tokens[i].charAt(0) == '-') {
stack.push(op2 - op1);
}
if (tokens[i].charAt(0) == '*') {
stack.push(op2 * op1);
}
if (tokens[i].charAt(0) == '/') {
stack.push(op2 / op1);
}
} else {
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.peek();
}
}
239. 滑动窗口最大值
题目链接: . - 力扣(LeetCode)
知识点: 单调队列,当然也可以大顶堆(包含value和index)解决
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums.length == 1) {
return nums;
}
int[] res = new int[nums.length - k + 1];
int index = 0;
MyQue myque = new MyQue();
for (int i = 0; i < k; i++) {
myque.add(nums[i]);
}
res[index++] = myque.peek();
for (int i = k; i < nums.length; i++){
myque.poll(nums[i - k]);
myque.add(nums[i]);
res[index++] = myque.peek();
}
return res;
}
/* 单调队列 */
public class MyQue {
Deque<Integer> deque = new LinkedList<Integer>();
void poll(int val) {
if (!deque.isEmpty() && val == deque.peek()){
deque.poll();
}
}
void add(int val) {
while(!deque.isEmpty() && val > deque.getLast()){
deque.removeLast();
}
deque.add(val);
}
int peek() {
return deque.peek();
}
}
}
347.前 K 个高频元素
题目链接: . - 力扣(LeetCode)
知识点: hashmap+小顶堆
class Solution {
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}
PriorityQueue<int[]> pq = new PriorityQueue<int[]>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] != o2[0] ? o1[0] - o2[0] : o2[0] - o1[0];
}
});
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
pq.offer(new int[]{entry.getValue(), entry.getKey()});
if (pq.size() > k) {
pq.poll();
}
}
int[] res = new int[k];
int index = 0;
while(!pq.isEmpty()) {
res[index++] = pq.poll()[1];
}
return res;
}
}