剑指offer---不修改数组找出重复的数字

题目描述

在一个长度为n+1的数组里的所有数字都在1-n之间,所以数组中至少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的数组。例如,如果输入长度为8的数组{2,3,5,4,3,2,6,7},对应的输出是重复的数字2或3.

题解

  1. 利用额外的数组空间或者哈希表做判断。
  2. 利用二分的思想把数字从中间分为两部分,前面一半为1-m,后面为m+1-n。如果1-m的数字个数超过m,那么这一半的区间里一定包含重复数字,否则另一半区间一定包含重复数字。
    代码实现(Java):时间复杂度:O(nlogn) .空间复杂度:O(1)
public static int getDuplication(int[] num){
        if (num == null || num.length == 0){
            return -1;
        }
        int start = 1,end = num.length - 1;
        while (start <= end){
            int middle = (start + end) >> 1;
            int count = count(num,start,middle);
            if (end == start){
                if (count > 1){
                    return start;
                }
                else {
                    break;
                }
            }
            if (count > (middle - start + 1)){
                end = middle;
            }else {
                start = middle + 1;
            }
        }
        return -1;
    }

    private static int count(int[] num, int start, int middle) {
        if (num == null){
            return 0;
        }
        int count = 0;
        for (int i = 0;i < num.length;i++){
            if (num[i] >= start && num[i] <= middle){
                count++;
            }
        }
        return count;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值