滑动最大窗口蛮力方法
Sliding Maximum window brute force method
给定一个大的整数数组和一个大小为'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;
}
相关文章:
- 当可输入框在窗口中处于活动状态时获得通知的任何方法
- 如何在窗口过程方法中检测击键?
- 设置窗口几何图形特性的正确方法
- 删除父/子窗口层次结构的最佳方法
- Gtkmm - 关闭窗口然后显示另一个窗口的正确方法
- 主窗口的新方法不可见
- 全局挂钩 DLL 仅在 C# 主窗口处于活动状态/前台时调用 C# 回调方法
- 有没有更好的方法来移动窗口
- 在 c++ 生成器中检测绘制线的窗口坐标的最佳方法
- 尝试使用窗口注册表中的路径和 DeleteFile() 方法删除.exe文件
- 在QT中的两个窗口之间进行通信的最佳方法是什么?
- 如何在WebBrowser控件窗口中生成异常.MFC中实现的外部方法
- 当用户更改密码时,哪个窗口 API 调用?钩住这个 API 的好方法是什么
- 有没有什么方法可以让窗口出现,但不让SFML中的cmd出现
- Qt C++从另一个类访问窗口方法
- 在C++窗口代码中有没有任何方法可以阻止鼠标移动到窗口边界之外
- C++:通过进程id、进程句柄和标题名称从进程中获取唯一窗口的窗口句柄的最佳方法
- 单击“关闭控制台窗口”结束 C++ 控制台程序是正确的方法
- 有什么方法可以判断分叉/执行Qt应用程序的主窗口何时显示?
- 在窗口中的屏幕上获取坐标像素数据的简单方法