其实无论是你这里的+N还是taocp里面求逆序中的改用相反数,本质都相同,都是使用了数据中一些没有被使用的bit位。
而对于这道题目,在n <2^31时,如果可以这样做,还有更加简单的方法。
直接将原数组的最高比特位看作一个比特位数组就可以了

C/C++ code

bool duplicate=false;
for(i=0;i<N;i++){
   int x=abs(a[i]);
   if(a[x-1]<0){
      duplicate=true;
      break;
   }else{
      a[x-1]=-a[x-1];
   }
}
for(i=0;i<N;i++){
    a[i]=abs(a[i]);
}
return duplicate;

...
]]>




Comments

Good.Be the first to comment on this entry.

Post comment

comment has COPYRIGHT too!

Note: Commenter is allowed to use '@User+blank' to automatically notify your reply to other commenter. e.g, if ABC is one of commenter of this post, then write '@ABC '(exclude ') will automatically send your comment to ABC. Using '@all ' to notify all previous commenters. Be sure that the value of User should exactly match with commenter's name (case sensitive).