法1:使用HashSet
Python
class Solution:
def findRepeatDocument(self, documents: List[int]) -> int:
h = set()
for item in documents:
if item in h:
return item
else:
h.add(item)
Java
public int findRepeatNumber(int[] array) {
Map<Integer, Integer> numToCountMap = new HashMap<>();
for (int num : array) {
if (numToCountMap.containsKey(num)) {
return num;
} else {
numToCountMap.put(num, 1);
}
}
return -1;
}
法2:使用索引=>值映射
虽然不是很好理解。。
class Solution {
public int findRepeatDocument(int[] documents) {
int i = 0;
while(i < documents.length) {
if(documents[i] == i) {
i++;
continue;
}
if(documents[documents[i]] == documents[i]) return documents[i];
int tmp = documents[i];
documents[i] = documents[tmp];
documents[tmp] = tmp;
}
return -1;
}
}
##Solution1:
20180910更新。利用数组做一次hash映射,时间复杂度为
O
(
n
)
O(n)
O(n),空间复杂度
O
(
n
)
O(n)
O(n).
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
int hash[length];
memset(hash, 0, sizeof(hash));
for (int i = 0; i < length; i++) {
hash[numbers[i]]++;
if (hash[numbers[i]] >= 2) {
*duplication = numbers[i];
return true;
}
}
return false;
}
};
##Solution2:
参考网址:https://www.nowcoder.com/profile/4747275/codeBookDetail?submissionId=16801123
思路:不需要额外的数组或者hash table来保存,题目里写了数组里数字的范围保证在0 ~ n-1 之间,所以可以利用现有数组设置标志,当一个数字被访问过后,可以设置对应位上的数 + n,之后再遇到相同的数时,会发现对应位上的数已经大于等于n了,那么直接返回这个数即可。
点评:对于此类问题很好的思路。值得特殊记一下!
时间复杂度
O
(
n
)
O(n)
O(n),空间复杂度
O
(
1
)
O(1)
O(1).
20180910晚:思路确实巧妙啊~~~
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
int index;
for(int i = 0; i < length; i++) {
index = numbers[i];
if(index >= length) {
index -= length;
}
if(numbers[index] > length) {
*duplication = index;
return true;
}
numbers[index] += length;
}
return false;
}
};