剑指offer java no.03B

本文介绍了一种使用二分法在不修改原始数组的前提下查找重复数字的方法。通过不断缩小搜索范围来定位重复数值,最终实现高效查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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也出现了两次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值