【问题标题】:Counting appropriate number of subarrays in an array excluding some specific pairs?计算数组中适当数量的子数组,不包括某些特定对?
【发布时间】:2015-08-15 15:55:51
【问题描述】:

假设我有一个这样的数组:

1 2 3 4 5 

给定对是(2,3),那么其中不存在 (2,3) 的可能子数组的数量将是,,

1. 1
2. 2
3. 3
4. 4
5. 5
6. 1 2
7. 3 4
8. 4 5
9. 3 4 5

所以,答案将是9

显然,这样的配对可以更多。

现在,我想到的一种方法是 O(n^2),它涉及找到最大长度 n 的所有此类元素。我能做得更好吗?谢谢!

【问题讨论】:

  • 你的意思是连续子数组(如果不是,你的例子是错误的,例如 [1, 3])?
  • 该数组中可以有重复的数字吗?
  • @Amit,子数组显然意味着连续的元素。
  • @Sumurai8,如果原始数组包含重复的数字并且它们形成一个子数组并且不是所需对的一部分,是的。 :)

标签: arrays algorithm


【解决方案1】:

我们看看,这个adhoc伪代码应该是O(n):

array = [1 2 3 4 5]
pair = [2 3]
length = array.length
n = 0
start = 0

while (start < length)
{
    # Find next pair

    pair_pos = start
    while (pair_pos < length) and (array[pair_pos,pair_pos+1] != pair)   # (**1)
    {
        pair_pos++
    }

    # Count subarrays

    n += calc_number_of_subarrays(pair_pos-start)  # (**2)

    # Continue after the pair

    start = pair_pos+2
}

print n

注意**1:这似乎涉及外循环内部的循环。由于数组的每个元素都被访问一次,所以两个循环加起来都是 O(n)。事实上,很容易将其重构为仅使用一个 while 循环。

注意**2:给定一个长度为 l 的数组,有 l+(l-1)+(l-2)+...+1 个子数组(包括数组本身)。这在 O(1) 中很容易计算,不涉及循环。 c/f 欧拉。 :)

【讨论】:

    【解决方案2】:

    您无需查找数组中有哪些子数组即可知道其中有多少。查找该对在数组中的位置最多需要 2(n-1) 次数组操作。然后你只需要用你从中提取的两个长度做一个简单的计算。长度为 3 的数组中子数组的数量例如为3 + 2 + 1 = 6 = (n(n+1))/2

    解决方案在给定数组[a, ..., p1, p2, ..., b] 中使用它,没有该对的子数组数量是[a, ..., p1] 的子数组数量+[p2, ..., b] 的子数组数量。如果存在多个这样的对,我们在 [p2, ..., b] 上重复相同的技巧,就好像它是整个数组一样。

    function amount_of_subarrays ::
      index := 1
      amount := 0
      lastmatch := 0
    
      while length( array ) > index do
        if array[index] == pair[1] then
          if array[index+1] == pair[2] then
            length2 := index - lastmatch
            amount := amount + ((length2 * (length2 + 1)) / 2)
            lastmatch := index
          fi
        fi
        index := index + 1
      od
    
      //index is now equal to the length
      length2 := index - lastmatch
      amount := amount + ((length2 * (length2 + 1)) / 2)
    
      return amount
    

    对于数组 [1, 2, 3, 4, 5] 和对 [2, 3],当两个 if 语句为真时,index 将为 2。 amount 将更新为 3,lastmatch 将更新为 2。将找不到更多匹配项,因此 lastmatch 是 2,index 是 5。amount 将是 3 + 6 = 9

    【讨论】:

    • 如果找到的属于该对的元素不是连续元素,这将如何工作?
    • 那么您的所有子数组都满足不包含该精确对的要求。
    • 如果这不是您所期望的,请编辑您的问题以阐明您的算法应该做什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2011-09-01
    • 2017-07-07
    • 2020-06-29
    相关资源
    最近更新 更多