在面试中无法弄清楚这一点。找到此数组中的最小循环?

时间:2018-04-20 03:31:54

标签: algorithm

我需要找到最小周期的长度。例如,[1,2,1,2]循环的长度为2.然后[1,2,1,2,1]的最小长度为2.然后长度为1,2,1,2 ,3应该是5,因为整个列表不重复(我不知道为什么这应该是5)。最小长度为1,2,1,2,1,1,2为5。

这是我尝试做的事情: 1.使用Dijkstra的算法,然后通过路径找到最小长度的cyle 我试着用一个缓慢而快速的指针然后找到了循环。然后我再次走过循环,找到循环的总长度。我也有一套不再通过相同的数字。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

有点不清楚“最小周期”意味着什么。话虽如此,我想你可能已经过了一点点。考虑它的一种更简单的方法是考虑抵消。例如,给定数组[1, 2, 1, 2, 1],您可以考虑在偏移给定量时此数组匹配的方式。当偏移它两次时,它完美排列:

offset = 2 cycle = [1, 2]
[1, 2, 1, 2, 1]
      [1, 2, 1, 2, 1]

offset = 5 cycle = [1, 2, 1, 2, 1]
[1, 2, 1, 2, 1, 1, 2]
               [1, 2, 1, 2, 1, 1, 2]

考虑到这一点,蛮力算法非常明确:

function findCycle(arr) {
  let offset = 1;

  while (offset < arr.length) {
    let suffix = arr.slice(offset)
    // compare - does the array match everywhere with this offset
    let matches = suffix.every((n, i) => n === arr[i])
    // is so this is the smallest cycle
    if (matches) break
    offset++
  }
  console.log(offset)
}

findCycle([1, 2, 1, 2, 3, 1, 2])
findCycle([1, 2, 1, 2, 1])
// degenerate case:
findCycle([1])
findCycle([]) // 1 but maybe should be zero?