最小元素是特定给定数字的子阵列数量

number of subarrays whose minimum element is a specific given number

本文关键字:阵列 数字 元素      更新时间:2023-10-16

给定数组,我想找到最小元素为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;
     }
  }
}