150. 逆波兰表达式求值
类似的题在上data structure这门课的时候就做过,这道题给了很多条件,保证表达是一定会得出有效数值,降低了解题的难度。使用stack操作运算,遇到数字则入栈;遇到运算符则取出栈顶两个数字进行计算,并将结果压入栈中。stack最后一个数值就是结果。
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for(String token: tokens){
if(token.equals("+")){
int operand1 = stack.pollLast();
int operand2 = stack.pollLast();
stack.offerLast(operand2 + operand1);
}else if(token.equals("-")){
int operand1 = stack.pollLast();
int operand2 = stack.pollLast();
stack.offerLast(operand2 - operand1);
}else if(token.equals("*")){
int operand1 = stack.pollLast();
int operand2 = stack.pollLast();
stack.offerLast(operand2 * operand1);
}else if(token.equals("/")){
int operand1 = stack.pollLast();
int operand2 = stack.pollLast();
stack.offerLast(operand2 / operand1);
}else{
stack.offerLast(Integer.parseInt(token));
}
}
return stack.pollLast();
}
}
239. 滑动窗口最大值
思路: 暴力解法就是不断滑动窗口,并在每次滑动中在窗口中找到最大的数值。另外的想法是用queue来模拟窗口,随着窗口移动,放进新元素,移除左边界的元素。但是如何维护窗口内的最大元素呢? 如果用priority queue,可以维护最大值,但是无法维护窗口里的数值。
这道题只需要记录窗口最大值,所以队列只需要保证queue把最大值放在最前端,队列元素由大到小排列,不需要记录所有的元素。也是就采用单调队列的策略。
在维护队列时,主要是pop和push的操作:代码随想录
- pop(value):如果窗口移除的元素value等于单调队列的出口元素,那么队列弹出元素,否则不用任何操作
- push(value):如果push的元素value大于入口元素的数值,那么就将队列入口的元素弹出,直到push元素的数值小于等于队列入口元素的数值为止
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
Deque<Integer> queue = new ArrayDeque<>();
int[] res = new int[nums.length - k + 1];
for(int i = 0; i < nums.length; i++){
//remove left element of the window
if(i >= k && !queue.isEmpty() && queue.getFirst() == nums[i - k]){
queue.pollFirst();
}
//add new element
while(!queue.isEmpty() && nums[i] > queue.getLast()){
queue.pollLast();
}
queue.offerLast(nums[i]);
if(i >= k - 1){
res[i - k + 1] = queue.getFirst();
}
}
return res;
}
}
347.前 K 个高频元素
思路:需要统计元素出现的频率,使用map进行记录。然后对频率进行排序。要达到O(nlogn)的效率,就需要 priority queue ,which based on a priority heap。
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> record = new HashMap<>();
PriorityQueue<int[]> queue = new PriorityQueue<>((pair1, pair2) -> pair2[1] - pair1[1]);
for(int num : nums){
record.put(num, record.getOrDefault(num, 0)+1);
}
for(var entry: record.entrySet()){
int[] tmp = new int[2];
tmp[0] = entry.getKey();
tmp[1] = entry.getValue();
queue.offer(tmp);
}
int[] ans = new int[k];
for(int i = 0 ; i < k; i++){
ans[i] = queue.poll()[0];
}
return ans;
}
}
1047

被折叠的 条评论
为什么被折叠?



