滑动最大窗口蛮力方法

Sliding Maximum window brute force method

本文关键字:方法 窗口      更新时间:2023-10-16

给定一个大的整数数组和一个大小为'w'的窗口,当窗口滑动到整个数组时,找出当前窗口中的最大值

我已经做了两个for循环,第一个循环工作正常,但内部循环不能根据不同的窗口大小正确移动。

我试着把它画在纸上,但我仍然不能得到一个公式的内循环

int main() {
    vector<int> arr = { -4, 2, -5, 3, 6 };
    int window = 3;
    for (int i = 0; i < arr.size() - window; i++)
    {
        int max = arr[i];
        for (int j = i + 1; j < i + window; j++)
        {
            cout << " i = "<<i << "j = " << j << endl;
            if (max < arr[j])
                max = arr[j];
        }
        cout << max << " " << endl;
    }

你的内循环是正确的。它是外循环,差1,它应该是:

for (int i = 0; i <= arr.size() - window; i++)

有5个元素的数组,窗口大小为3,最后一个窗口是array[2]array[4]arr.size() = 5。window = 3。5-3=2,你仍然需要迭代窗口的起始位置

试试这个:

#include <algorithm>
int main() {
  std::vector<int> arr = { -4, 2, -5, 3, 6 };
  int window = 3;
  for (std::size_t i = 0; i < arr.size() - window + 1; i++)
  // one of your bugs is here --------------------^           
  {
      int max = 0;
      // this way, it's easier to see how the window slides
      for (std::size_t j = 0; j < window; j++)
      {
          std:: cout << " i = "<<i << "j = " << j+i << std::endl;
          max=std::max(arr[i+j],max);
          // --------------^
          // i becomes the window's offset
          // j is the offset inside the window
          // using std::max eliminates a i+j twice with an if
          //  ... (and will be inlined anyway)
      }
      std::cout << max << " " << std::endl;
  }
  return 0;
}