最小元素是特定给定数字的子阵列数量
number of subarrays whose minimum element is a specific given number
给定数组,我想找到最小元素为x的所有子阵列的数量。其中x是一个给定的数字,该数字可能在数组中可能不存在或可能不存在数字x的多个出现。O(n)实施将是首选。
您有一个已知大小 n 的向量 vec 。然后,您可以将元素与 vec(i)与 x 的值进行比较。一旦找到 x 的值较高的值,该值可以是一组包含 x 的子向量的下限。您将继续在 vec 的元素上运行,可能会发生两件事:
1)您发现一个小于 x 的元素,然后该下限不再有效,然后继续搜索。
2)您找到 x ,因此,您可以保存相对于下限的相对位置,然后继续在索引上运行,直到找到小于 x 的值,所以您有上限。边界包含一组子阵列,其中x是最小值。计算所有可能的组合。
您是在案例1或2中,您将继续在索引上运行,直到找到另一个有效的范围,或者直到到达向量的末端为止。
int x;
std::vector<int> vec(n);
unsigned int l_bound = n; //initialize n to an invalid index
unsigned int r_bound;
unsigned int x_pos = n; //initialize x to an invalid index
unsigned int n_sub_arrays = 0;
// here we do something to assign values to vec and x
// here we count the number of subarrays
for (unsigned int i = 0; i<n; ++i)
{
if (vec(i) >= x)
{
if (l_bound == n) // if we are at the first value higher that x
{
l_bound = i;
if (vec(i) == x) // if this value is already x
{
x_pos = i;
}
}
}
else
{
if (x_pos == n) // x is not inside the bounds
{
l_bound = n; // the bounds are not valid
}
else
{
r_bound = i-1;
n_sub_arrays += (x_pos - l_bound+1)*(r_bound-x_pos+1);
l_bound = n;
x_pos = n;
}
}
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- OpenMP阵列性能较差
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 从char阵列中提取十六进制数字
- 如何将一个数字(大于8个字节)从字符阵列转换为其ASCII表示
- 如何在较高和较低数字的阵列中适应搜索算法(3N / 2)-2
- 通过2D阵列C 移动锯齿ZAG模式的数字
- 最小元素是特定给定数字的子阵列数量
- 整流波形(数字阵列)的平均值、RMS和过零次数c++
- 1D阵列中数字的频率
- 将符号指定给二维阵列中的数字
- 以将阵列中的数字范围映射为均匀随机1到100