面試的常考題,關注算法復雜度和空間,
假如是下面的方法判斷是否有重復
int a[MAX] = {0};
unsigned int x;
for(int i=0;i <n;i++)
{
//讀入x
if(a[x]==1)
{
//x重復出現了
}
else
{
a[x]=1;
}
}
那么,MAX比較大時就不合適了
但是可以把“用int數組記錄是否重復”改為“用每一個bit記錄是否重復”,于是變成:
int a[MAX] = {0};
unsigned int x;
const int iBitCount = 32;
for(int i=0;i <n;i++)
{
//讀入x
if(a[x/iBitCount]& (1 < <(x%iBitCount))!=0)
{
//x重復出現了
}
else
{
a[x/iBitCount] ¦= (1 < <(x%iBitCount));
}
}
另有,原地排序等O(1),排序后除重等
posted on 2008-04-22 22:47
fullfocus 閱讀(851)
評論(2) 編輯 收藏 所屬分類:
算法