给定大量的整数和大小的窗口,当窗口滑过整个数组时,找到窗口中的当前最大值。
我已经制作了两个for循环,第一个循环正常工作,但内循环不能根据不同的窗口大小正确移动。
我试图在纸上画画,但我仍然无法获得内循环的公式
POST /wp-login.php HTTP/1.1
Host: 192.168.18.138
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.8.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://192.168.18.138/wp-login.php
Cookie: s_fid=2692E4153C7D3D30-158A9B35CCC16635; s_nr=1473166726975; s_cc=true; s_sq=%5B%5BB%5D%5D; wordpress_test_cookie=WP+Cookie+check
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 104
log=admin&pwd=login&wp-submit=Log+In&redirect_to=https%3A%2F%2F192.168.18.138%2Fwp-admin%2F&testcookie=1
答案 0 :(得分:2)
你的内循环是正确的。这是你的外循环,它是1,它应该是:
for (int i = 0; i <= arr.size() - window; i++)
使用包含5个元素的数组且窗口大小为3,最后一个窗口为array[2]
到array[4]
。 arr.size()
为5. window
为3. 5-3 = 2,您仍然需要迭代该窗口的起始位置。
答案 1 :(得分:1)
试试这个:
#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;
}