按照一般思路,遍历整个数列,就可以找到那个单个的数,但此时的算法复杂度为O(n);
因此,我们可以采用一种更加方便的思路,使用分治算法求解
1.数列的长度一定为奇数,因此找数列的中位数,用该数分别和他前面一个数和后面一个数比较,若都不相同,则该数为所要找的单数
2.若等于前面一个数,那么求该数左边和右边的剩余数列的长度,单数一定在长度为奇数的那半边,递归寻找
3.若等于后面一个数,同样思路求解;
class QiuDanShu{
public QiuDanShu(){
}
public void qiujie(int a[] , int b, int c){
int mid = (b + c)/2;
if(c-b == 0) {
System.out.println("位置在:" + b);
System.out.println("单数为:" + a[c]);
return;
}
if(a[mid] != a[mid+1] && a[mid] != a[mid -1] ) {
System.out.println("位置在:" + mid);
System.out.println("单数为:" + a[mid]);
return;
}
else if(a[mid] == a[mid -1]){
if((c - mid - 1)%2 == 0 ) {
qiujie(a , mid+1, c);
}
else {
qiujie(a , b, mid-2);
}
}
else
{
if((mid-1-b)%2 == 0 ) {
qiujie(a , b, mid-1);
}
else {
qiujie(a , mid +2 , c);
}
}
}
}
public class TestDan {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a1[] = new int []{9,9,0};
int c = a1 .length;
QiuDanShu test1 = new QiuDanShu();
test1.qiujie(a1, 0, c-1);
}
}