1.快排,时间:O(nlog(n)),空间:O(1)
2.用一个HashMap,时间:O(n),空间:O(n)
顺序扫描数组,如果HashMap没有包含当前数字,就把这个数字放入HashMap,否则,就为重复数字。
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) {
map<int, int>M;
for (int i = 0; i < length; i++)
M[numbers[i]]++;
for (int i = 0; i < length; i++)
if (M[numbers[i]] > 1 )
{
duplication[0] = numbers[i];
return true;
}
return false;
}
};
3. 安排序列交换,时间:O(n),空间:O(1)
顺序扫描数组,判断当前扫描的每个数字是否满足 numbers[i]=i ,如果不满足,则说明这个数字不在对应的位置上,于是把将这个数字与numbers[numbers[i]]交换,如果扫描某个数字的过程中发现numbers[i]=numbers[numbers[i]],则说明numbers[i]在i 位置和numbers[i]位置出现了两次,所以是重复数字。
空间复杂度为什么是O(n)
:因为顺序遍历一个for循环,循环里面的while和n没关系,交换对于一个数来说最多 两次
(一次被动,一次主动[指的是让i==numbers[i]]),
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) {
for (int i = 0; i<length; i++)
{
while (i != numbers[i])
{
if (numbers[i] == numbers[numbers[i]])
{
duplication[0] = numbers[i];
return true;
}
swap(numbers[i], numbers[numbers[i]]);
}
}
return false;
}
};