剑指Offer(Java实现):数组中的重复数字(二分实现)

题目
一个数组,有重复数字,在不破坏数组的前提下,找到数组的任意一个重复数字

思路
一个数组比如有8个数字,取中间值4,按道理是比4小的数字有四个,如果比4小的数字或者比4大的数字大于4个,那重复的数字一定是在前四个或者后四个,取一半以后,再把前4或者后4分为一半,和2比较,直到找到重复的数字。

代码

public class T03 {
    public static int getnums(int nums[], int length){
        int start = 1;
        int end = length-1;
        while (end >= start){
            int mid = ((end-start)/2)+start;

            int count = countRange(nums,length,start,mid);
            if(end == start){
                if(count > 1)
                    return start;
                else
                    break;
            }
            if(count > (mid-start+1))
                end = mid;
            else
                start = mid + 1;
        }
        return -1;
    }

    private static int countRange(int[] nums, int length, int start, int end) {
        if(nums == null)
            return 0;

        int count = 0;

        for(int i = 0;i<length;i++){
            if(nums[i]>=start&&nums[i]<=end)
                ++count;
        }
        return count;
    }

    public static void main(String[] args) {
        int[] nums1 = {2,3,5,4,3,2,6,7};
        System.out.println(getnums(nums1,8));
    }
}

发布了49 篇原创文章 · 获赞 4 · 访问量 2513

猜你喜欢

转载自blog.csdn.net/weixin_42040292/article/details/104055593