笔试之栈和队列总结

今天来总结一下栈和队列,不多说直接看题

       

 

 要求求最小元素要在O(1)时间复杂度内,但是一般求最小元素需要遍历栈至少O(n),这里就会想到用空间换时间,使用两个栈来实现最小栈,看代码:

 1 public class _155最小栈 {
 2     private Stack<Integer> stack;
 3     private Stack<Integer> stack1;
 4     public _155最小栈() {
 5        stack = new Stack<>();
 6        stack1 = new Stack<>();
 7     }
 8     public void push(int x) {
 9         stack.push(x);
10         if(stack1.isEmpty()){
11             stack1.push(x);
12         }else {
13                 stack1.push(Math.min(x,stack1.peek()));
14         }
15     }
16     public void pop() {
17         stack.pop();
18         stack1.pop();
19     }
20     public int top() {
21         return  stack.peek();
22     }
23     public int getMin() {
24         return stack1.peek();
25     }
26 }
  • 滑动窗口最大值(https://leetcode-cn.com/problems/sliding-window-maximum/)

 

这个题首先可以用暴力,但是会超时,也可以用队列,但是这里介绍一种更巧妙地方法,看代码,其实主要还是维护最大值的索引

 1     public static  int[] maxSlidingWindow(int[] nums, int k) {
 2         int[] dp = new int[nums.length - k + 1];
 3         int maxIndex = 0;
 4         for (int i = 1; i < k; i++) {
 5             if(nums[i] > nums[maxIndex]) maxIndex = i;
 6         }
 7         for (int i = 0; i < dp.length; i++) {
 8             int r = i + k -1;
 9             if(maxIndex < i){//最大值索引不在窗口内,进行重新找最大索引
10                 maxIndex = i;
11                 for (int j = i + 1; j <= r; j++) {
12                     if(nums[j] > nums[maxIndex]) maxIndex = j;
13                 }
14             }else  if (nums[r] > nums[maxIndex]){
15                 maxIndex = r;
16             }
17             dp[i] = nums[maxIndex];
18         }
19         return dp;
20     }

 

posted @ 2020-08-05 22:15  tingting_lh  阅读(121)  评论(0)    收藏  举报