剑指Offer-03-数组中重复的数字

剑指Offer-03数组中重复的数字

描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是2或者3。存在不合法的输入的话输出-1

数据范围:0\le n \le 10000 \0≤n≤10000

进阶:时间复杂度O(n)\O(n) ,空间复杂度O(n)\O(n)

代码

法一:通过数组索引位置判断

    public static int getduplicate01(int[] arr){
        if (arr==null||arr.length==0){
            return -1;
        }
        int len = arr.length;
        for (int i = 0; i < len; i++) {
            while (arr[i]!=i){
                if (arr[arr[i]]==arr[i])
                    return arr[i];
                int tmp = arr[i];
                arr[i] = arr[tmp];
                arr[tmp] = tmp;
            }
        }
        return  -1;
    }

法二:利用HashSet去重的特性

    public static int getduplicate02(int[] arr){
        if (arr==null||arr.length==0){
            return -1;
        }
        HashSet<Integer> solution = new HashSet<>();

        for (int i : arr) {
            if (solution.contains(i)){
                return i;
            }else{
                solution.add(i);
            }
        }
        return -1;
    }

posted @ 2022-10-30 23:42  进阶的蜗牛  阅读(12)  评论(0编辑  收藏  举报