• 队列的最大值


    题目:

    请定义一个队列并实现函数max得到队列里的最大值,要求函数max、push_back、pop_front的时间复杂度都是O(1)

    思路:

    利用一个双向队列存储当前队列中最大值以及之后可能的最大值。在定义题目要求功能的队列时,除了定义一个队列data存储数值,还要额外用一个队列maximum存储可能的最大值;此外,还要定义一个数据结构,用于存放数据以及当前index的值,用于删除时确定是否删除maximum中的最大值。

     1 import java.util.ArrayDeque;
     2 
     3 public Solution {
     4     private ArrayDeque<InternalData> data = new ArrayDeque<InternalData>();
     5     private ArrayDeque<InternalData> maximum = new ArrayDeque<InternalData>();
     6 
     7     private class InternalData {
     8         int number;
     9         int index;
    10 
    11         public InternalData(int number, int index) {
    12             this.number = number;
    13             this.index = index;
    14         }
    15 
    16     }
    17 
    18     private int curIndex;
    19 
    20     public void pop_front() {
    21         if(data.isEmpty()) {
    22             System.out.println("queue is empty");
    23             return;
    24         }
    25 
    26         InternalData curData = data.removeFirst();
    27         if(curData.index == maximum.getFirst().index) {
    28             maximum.removeFirst();
    29         }
    30     }
    31 
    32     public int max() {
    33         if(maximum == null) {
    34             System.out.println("queue is empty");
    35             return 0;
    36         }
    37 
    38         return maximum.getFirst().number;
    39     }
    40 
    41     public void push_back(int number) {
    42         InternalData curData = new InternalData(number, curIndex);
    43         data.addLast(curData);
    44 
    45         while(!maximum.isEmpty() && maximum.getLast().number < number) {
    46             maximum.removeLast();
    47         }
    48 
    49         maximum.addLast(curData);
    50         curIndex++;
    51     }
    52 
    53     public static void main(String[] args) {
    54         Solution s = new Solution();
    55 
    56         // {2}
    57         s.push_back(2);
    58         System.out.println(s.max());
    59 
    60         s.push_back(3);
    61         // {2,3}
    62         System.out.println(s.max());
    63 
    64         s.pop_front();
    65         // {3}
    66         System.out.println(s.max())
    67 
    68     }
    69 }
  • 相关阅读:
    117. Populating Next Right Pointers in Each Node II
    50. Pow(x, n)
    494. Target Sum
    Word Ladder
    HDU 4417
    POJ 2104
    POJ 3277
    【转】图论500题
    POJ 2991
    POJ 1436
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10341922.html
Copyright © 2020-2023  润新知