查找给定值的所有数组子序列

Find all array subsequences of a given value

我正在寻找一种给出如下列表的算法:

[1, 1, 2, 1, 1, 5, 1, 1, 1, 1, 2, 1]

可以找到并 return 给定值的所有子序列。例如,如果给定值 1,函数将 return [[1, 1], [1, 1], [1, 1, 1, 1], [1]].

我认为这类似于求和数组的所有子序列或查找给定字符串的所有子序列等问题,但算法从来都不是我的强项。答案可以是伪代码或语言不可知论。如果您不介意,能否解释一下解决方案的复杂性?

如果有帮助,我可以解释我需要这个做什么。如果你想要那个,请评论。

我们可以通过扫描数组两次来以 O(n) 的时间复杂度完成此操作。伪代码:

//use an array list so we can access element at an index in O(1) time
outputArrays = new ArrayList<int[]> //list of arrays

//loop to declare arrays of outputs - this scans each element once
int currLen = 0;
for (item in inputArray) {
 if (item = itemToLookFor) {
  currLen++;
 }else if (currLen > 0) {
  currLen = 0;
  outputArrays.add(new int[currLen]);
 }
}

//loop to actually populate the output - this scans each element once
currLen = 0;
currIndex = 0;
for (item in inputArray) {
 if (item = itemToLookFor) {
  outputArrays.getElement(currIndex)[currLen] = item;
  currLen++;
 }else if (currLen > 0) {
  currLen = 0;
  currIndex++;
 }
}

如果有什么我可以澄清的,请告诉我。

a 为初始数组,res - 结果序列数组,curSeq - 当前序列,given_value - 给定值。

res = []
curSeq = []
for i = 1..length(a)
    if a[i] != given_value
        if curSeq has at least one item
            append curSeq to res
        end if
        curSeq = []
    else
        append given_value to curSeq
    end if
end for
if curSeq has at least one item
    append curSeq to res
end if

如您所见,时间复杂度为 O(n) 其中 n 是初始数组的长度。

这里是 O(n) 解决方案。 这里 arr 是序列的输入数组, sequence 是子序列的数组。您可以将序列保存到另一个数组中作为您的答案。

arr = [1, 1, 2, 1, 1, 5, 1, 1, 1, 1, 2, 1]; // here is your
selectNumber = 1 //take input for selected input
sequence = [];
for (i: 0 to arr.length) {
  if (arr[i] == selectNumber) {
    sequence.push(selectNumber);
  } else {
    if(sequence.length > 0) {
      print sequence;
      sequence = [] // empty sequence array as it is already printed or saved
    }
  }
}

if (sequence > 0) {
  print sequence; // last sequence if exist
}