https://www.lintcode.com/problem/minimum-cycle-section/description
这题据说是头条笔试第一题,看了下 对非ACMer而言,或者我这种比较菜 而且忘得差不多的 真是有点难啊......
参考了这里 https://www.jiuzhang.com/solution/minimum-cycle-section/
复习一下kmp:
next[i] = v,表示如果跟pat[i]不匹配,那么就从pat[v]重新开始尝试匹配
想下循环节的特点:
index: 0 1 2 3 4 5 6 7
数组: 1 2 1 2 1 2 3 1
next: -1 0 1 2 3 4 0 1
可以看出来 循环节长度+next[end] - 1 = end -1
可以加上上面的序列是121212验证一下上面吗的式子
end 的index是6
class Solution { public: /** * @param array: an integer array * @return: the length of the minimum cycle section */ int minimumCycleSection(vector<int> &array) { vector<int> next(array.size()+1, 0); int i = 0, j = -1; next[0] = -1; while (i < array.size()) { if (j == -1 || array[i] == array[j]) { i++; j++; next[i] = j; } else { j = next[j]; } } return i - next[i]; // for (int i = 0; i < array.size(); i++) } };