题目:一个大小为n的数组,里面的数都属于范围[0, n-1],有不确定的重复元素,找到至少一个重复元素,要求O(1)空间和O(n)时间。
这个问题分析的连接地址:http://blog.csdn.net/morewindows/article/details/8204460#java, 这位博主已经把解决问题的思路分析得很清晰了,但该算法有一个缺点,就是会改变原来的数组, 下面我给出我自己的解法
public class RepeatNum {
public static int NO_REPEAT_FLAG=-1;
public int findRepeatNum2(int[] arr, int len){
int temp=0;
for(int i=0; i<len; i++){
if((temp&(1<<arr[i]))!=0){
return arr[i];
}else{
temp=(temp|(1<<arr[i]));
}
}
return NO_REPEAT_FLAG;
}
public static void main(String[] args){
RepeatNum obj = new RepeatNum();
int[] arr = {1,2,3,0,5,6,7,0};
System.out.println(obj.findRepeatNum2(arr, arr.length));
}
}
如有错误的地方,望指正!