给定一个整数数组和一个数k,计算长度为k的每个子数组的最大值
Given an array of integers and a number k, compute the maximum values of each subarray of length k
问题:给定一个整数数组和一个数字k,其中1<=k<=阵列的长度,计算长度为k的每个子阵列的最大值。
在O(n)时间和O(k)空间中执行此操作。您可以在适当的位置修改输入数组,而不需要存储结果。你可以在计算它们的时候简单地打印出来。
示例:给定array=[10,5,2,7,8,7]和k=3,我们应该得到:[10,7,8.8],因为:
10=最大(10,5,2)
7=最大(5,2,7)
8=最大(2,7,8)
8=最大(7,8,7)
想法:
我想到了使用std::max_element()函数来解决这个问题,在这个函数中我注意到了一个模式。使用上面的示例
std::max_element(0,2)=10,其中0是迭代器的起始位置,2是迭代程序的结束位置。
std::max_element(1,3)=7
std::max_element(2,4)=8
std::max_element(3,5)=8
因此,对于任何k,第一迭代器将总是从0到n-2,其中n是向量或数组的大小,并且max_element的右迭代器总是从k-1到n-1。
虽然为k的各种值指定正确的迭代器并不太直接。正如你从我的代码中看到的,我坚持了这一部分,但我相信我的想法是合理的。我希望我把这个想法说明给其他人理解。
代码:
#include <iostream>
#include <vector>
#include <random>
#include <ctime>
// Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values
// of each subarray of length k.
// For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get : [10, 7, 8, 8], since :
// 10 = max(10, 5, 2)
// 7 = max(5, 2, 7)
// 8 = max(2, 7, 8)
// 8 = max(7, 8, 7)
// Do this in O(n) time and O(k) space. You can modify the input array in-place and you do not need to
// store the results. You can simply print them out as you compute them.
void printKMax(std::vector<int>& nums, int k)
{
int n = nums.size();
int i = 0;
int j = k - 1;
std::vector<int>::iterator it;
while (j <= n - 1)
{
it = std::max_element(nums.begin() + i, );
i++;
j++;
std::cout << *it << " ";
}
}
int main()
{
std::vector<int> nums = { 10, 5, 2, 7, 8, 7};
int k = 3;
printKMax(nums, k);
std::cin.get();
}
问题:我在为std::max_element的正确部分找到适用于k的各种值的公式时遇到问题。如有任何帮助,我们将不胜感激。
您保留变量i
和j
作为检查范围的开始和结束,因此您需要将std::max_element
专门应用于该范围。您正在寻找替代:
it = std::max_element(nums.begin() + i, );
带有:
it = std::max_element(nums.begin() + i, nums.begin() + j + 1);
注意+ 1
部分。这是因为STL的标准约定是在右侧独占的范围内操作。