微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

最大滑动窗口问题我的解决方案无效,但非常相似的解决方案有效,而且我不明白为什么

如何解决最大滑动窗口问题我的解决方案无效,但非常相似的解决方案有效,而且我不明白为什么

我正在尝试解决“滑动窗口最大值”问题(给定一个数组和一个整数m,为每个大小为m的连续子数组找到最大值)。

我实际上设法解决了这个问题,但是我的代码对于一个测试用例来说太慢了。在geeksforgeeks上,我找到了与我的解决方案非常相似的解决方案,但是它可以正常工作,我不明白为什么。有人知道发生了什么吗?

我正在用Java编程,这是两个代码

我的:

  public static void solve(int[] a,int m) {

int n = a.length;
arraydeque<Integer> pico = new arraydeque<Integer>();
for(int i = 0; i < m-1; i++) {

  while(!pico.isEmpty() && a[pico.getLast()] <= a[i]) {

    pico.removeLast();

  }
  pico.addLast(i);

}
for(int i = m-1; i < n; i++) {

  while(!pico.isEmpty() && a[pico.getLast()] <= a[i]) {

    pico.removeLast();

  }
  pico.addLast(i);
  if(pico.getFirst()+m <= i) {

    pico.removeFirst();

  }
  System.out.printf("%d ",a[pico.getFirst()]);

}

Geeksforgeeks:

static void printMax(int arr[],int n,int k) 
{ 
    // Create a Double Ended Queue,Qi that will store indexes of array elements 
    // The queue will store indexes of useful elements in every window and it will 
    // maintain decreasing order of values from front to rear in Qi,i.e.,// arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order 
    Deque<Integer> Qi = new LinkedList<Integer>(); 

    /* Process first k (or first window) elements of array */
    int i; 
    for (i = 0; i < k; ++i) { 
        // For every element,the prevIoUs smaller elements are useless so 
        // remove them from Qi 
        while (!Qi.isEmpty() && arr[i] >= arr[Qi.peekLast()]) 
            Qi.removeLast(); // Remove from rear 

        // Add new element at rear of queue 
        Qi.addLast(i); 
    } 

    // Process rest of the elements,from arr[k] to arr[n-1] 
    for (; i < n; ++i) { 
        // The element at the front of the queue is the largest element of 
        // prevIoUs window,so print it 
        System.out.print(arr[Qi.peek()] + " "); 

        // Remove the elements which are out of this window 
        while ((!Qi.isEmpty()) && Qi.peek() <= i - k) 
            Qi.removeFirst(); 

        // Remove all elements smaller than the currently 
        // being added element (remove useless elements) 
        while ((!Qi.isEmpty()) && arr[i] >= arr[Qi.peekLast()]) 
            Qi.removeLast(); 

        // Add current element at the rear of Qi 
        Qi.addLast(i); 
    } 

    // Print the maximum element of last window 
    System.out.print(arr[Qi.peek()]); 
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。