Пример #1
0
  public static int[] maxInWindow(int[] array, int k) {
    if (k <= 0 || array == null || array.length == 0) {
      System.out.println("invalid input");
      return new int[0];
    }
    int len = array.length;
    int[] max = new int[len];
    if (k == 1) {
      System.arraycopy(array, 0, max, 0, len); // 复制一份,不影响原数组
    } else {
      LinkedList<Item> queue = new LinkedList<Item>();
      for (int i = 0; i < len; i++) {
        Item curItem = new Item(array[i], i);
        if (queue.isEmpty()) {
          queue.addLast(curItem);
        } else {
          Item head = queue.getFirst();
          int headIndex = head.getIndex();

          // 如果队首元素已不在窗口内,则删除
          if (headIndex < (i - k + 1)) {
            queue.removeFirst();
          }

          // 插入元素
          while (!queue.isEmpty()) {
            Item tail = queue.getLast();
            int tailValue = tail.getValue();
            if (tailValue < array[i]) {
              queue.removeLast();
              if (queue.isEmpty()) {
                queue.addLast(curItem);
                break;
              }
            } else if (tailValue > array[i]) {
              queue.addLast(curItem);
            } else {
              break;
            }
          }
        }

        // 每次操作后,队首元素为当前窗口的最大值
        if (!queue.isEmpty()) {
          max[i] = queue.getFirst().getValue();
        }
      }
    }
    return max;
  }