class Solution {
public int findRepeatDocument(int[] documents) {
int i = 0;
while (i < documents.length) {
// 判断当前index=documents[index]
// 不相等,就把当前documents[index]换到正确的下标处,如果那个下标已经有相等的占据了,就说明重复了
int curValue = documents[i];
while (curValue != i) {
if (documents[curValue] == curValue) {
return curValue;
} else {
swap(documents, i, curValue);
}
curValue = documents[i];
}
i++;
}
return -1;
}
public void swap(int[] documents, int a, int b) {
int tmpt = documents[a];
documents[a] = documents[b];
documents[b] = tmpt;
}
}
共以下 3 个回答
解题思路
– 最简单的思路是使用HashMap,但是需要额外的空间
– 优化就是使用0 ≤ documents[i] ≤ n-1的特性,用原数组进行一些重复性的校验
– 判断当前index=documents[index]
– 不相等,就把当前documents[index]换到正确的下标处,如果那个下标已经有相等的占据了,就说明重复了(如果是完全不重复的,那么理论上可以遍历到最后一个)
【题解1】
原地交换法,时间复杂度O(N),空间复杂度O(1)。