剑指offer java no.03B

no.03B: 在长度为n+1的数组里的所有数字都在1~n的范围内,所以数组中至少有一个数字是重复的。找出数组中重复的数字,但是不能改变数组。{2,3,5,4,3,2,6,7},那么对应输出的数字就应该是2或者3

两种思路:

  1. 运用辅助数组
  2. 二分法
public class NO03B {
    public static void main(String[]args){
        int[] numbers = {2,3,5,4,3,2,6,7};
        int lenth = numbers.length;
        C c = new C();
        System.out.println(c.getDuplication(numbers, lenth));
    }

}

class C{
    int getDuplication(int[] numbers, int length){
        if(numbers == null || length == 0){
            return -1;
        }

        int start = 1, end = length - 1;
        while(start <= end){
            int middle = ((end - start) >> 1) + start;
            int count = countRange(numbers, length, start, middle);
            if (start == end){
                if (count > 1){
                    return start;
                }
                break;
            }
            if (count >  (middle - start + 1)){
                end = middle;
            }else{
                start = middle + 1;
            }
        }

        return -1;
    }

    int countRange( int[] numbers, int lenth, int start, int end){
        if (numbers == null){
            return 0;
        }
        int count = 0;
        for (int i = 0; i < lenth; i++){
            if (numbers[i] >= start && numbers[i] <= end){
                count++;
            }
        }
        return count;
    }
}

该算法不能找出数组中重复的数字2。因为1~2有两个数字,这个范围2也出现了两次。

猜你喜欢

转载自blog.csdn.net/TaylorSwift_1989/article/details/88957062