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

时间:2014-02-07 15:21:27

标签: c++ algorithm arrays

给定一个数组,我想找到最小元素为x的所有子数组的数量。 其中x是数组中可能存在或可能不存在的给定数字,或者数字x中可能出现多次出现的数字。 O(n)实施将是优选的。

1 个答案:

答案 0 :(得分:0)

你有一个已知大小 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;
     }
  }
}