题目:给定一个长度为N的数组,其中每个元素的取值范围都是1到N。判断数组中是否有重复的数字。(原数组不必保留)
方法1.
对数组进行排序(快速,堆),然后比较相邻的元素是否相同。
时间复杂度为O(nlogn),空间复杂度为O(1)。
方法2.
使用bitmap方法。
定义长度为N/8的char数组,每个bit表示对应数字是否出现过。遍历数组,使用 bitmap对数字是否出现进行统计。
时间复杂度为O(n),空间复杂度为O(n)。
方法3.
遍历数组,假设第 i 个位置的数字为 j ,则通过交换将 j 换到下标为 j 的位置上。直到所有数字都出现在自己对应的下标处,或发生了冲突。
时间复杂度为O(n),空间复杂度为O(1)。
方法3示例代码如下
#include<iostream> #include<ctime> using namespace std; //判断数组中是否包含重复数字 const int MAX= 10; bool isDuplicate(int val[]) { for(int i=0;i<MAX;i++) { if(val[i]!=i) { if(val[i] != val[val[i]]) swap(val[i],val[val[i]]); else return true; } } return false; } int main() { int val[MAX]; srand((unsigned)time(NULL)); cout<<"init data:"<<endl; for(int i=0;i<MAX;i++) { int tmp=rand()%MAX; val[i]=tmp; cout<<tmp<<" "; } cout<<endl; bool flag=isDuplicate(val); if(flag) cout << "has duplicate elem" << endl; else cout << "no duplicate elem" << endl; }
srand((unsigned)time(NULL));
time()头文件为ctime.这句话不要程序每次运行结果都一样。
: