题目一:在一个长度为n的数组中,所有的数字都在0~n-1的范围里,数组中的某些数字是重复的,但不知道有几个数字重复了,请求出数组中任意一个重复的数字。
解题思路:
- 首先想到的肯定是排序,然后再次遍历来查看有无重复,这样的时间复杂度至少为O(nlogn)
- 然后第二种想到的方法就是hash表,或者利用unordered_set,因为其内部实现也是利用hash表。具体过程就是遍历数组中的每一个元素,然后在hash表中查找是否存在相同元素,如果存在则说明重复,如果不存在则插入hash表。这个算法时间复杂度为o(n),空间复杂度为o(n),因为建立一个hash表。
- 利用交换元素的方法。遍历每一个元素,假设在位置i上的元素为j,先比较位置i和j上的元素是否相同,如果相同则存在重复,如果不相同则交换两个位置上的元素,直到找到位置i上的元素为i,然后接着遍历下一个元素。这个方法的时间复杂度为O(n),空间复杂度为O(1)。
思路二代码:
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) {
if (length<=0) return false;
for(int i=0;i<length;i++)
{
if(numbers[i]<0 ||numbers[i]>length-1)
{
return false;
}
}
unordered_set<int> s;
int flag=0;
for(int i=0;i<length;i++)
{
if(s.find(numbers[i])==s.end())
{
s.insert(numbers[i]);
}
else{
flag=1;
*duplication=numbers[i];
break;
}
}
return flag==1? true:false;
}
};
思路三代码:
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) {
if (length<=0) return false;
for(int i=0;i<length;i++)
{
if(numbers[i]<0 ||numbers[i]>length-1)
{
return false;
}
}
for(int i=0;i<length;i++)
{
while(i!=numbers[i])
{
if(numbers[i]==numbers[numbers[i]])
{
*duplication=numbers[i];
return true;
}
else
{
swap(numbers[i],numbers[numbers[i]]);
}
}
}
return false;
}
};
题目二:不修改数组找出重复的元素:在一个长度为n+1的数组里的所有数字都在1~n的范围内,所以数组中至少有一个数字是重复的,请找出数组中任意一个重复的数字,但是不能修改数组。
解题思路:因为不能修改数组,所以不能接着用上面的那个交换的方法。具体思路是:因为数字范围比数组个数大1,所以至少会有一个数字重复。我们可以利用二分法将范围进行划分为[1,m],(m,n],然后计算数组在范围[1,m]中的个数k,如果个数k大于m,则继续在前面这个范围中查找,否则在后面的范围查找。依次循环。
解题代码:
#include <iostream>
using namespace std;
int countrange(const int *numbers,int length,int start,int mid)
{
int res=0;
for(int i=0;i<length;i++)
{
if(numbers[i]<=mid &&numbers[i]>=start)
{
res++;
}
}
return res;
}
int getDunplication(const int *numbers,int length)
{
if(length<=0||numbers==nullptr)
return -1;
int n=length-1;//数组的长度比给数字的范围大1
//快速实现二分法
int start=1;
int over=n;
while(start<=over)
{
int mid=start+((over-start)>>1);
int ct=countrange(numbers,length,start,mid);//区间[start,mid]之间的数
if(start==over)
{
if(ct>1) return start;
else break;
}
if(ct>(mid-start+1))
{
over=mid;
}
else
{
start=mid+1;
}
}
return -1;
}
int main()
{
int a[]={2,3,5,4,3,2,6,7};
int length=8;
int result=getDunplication(a,length);
if(result==-1)
{
cout<<"error"<<endl;
}
else
{
cout<<"the dunplication is "<<result<<endl;
}
return 0;
}