[剑指OFFER]之排序:JZ3 数组中重复的数字

1.题目

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。

2.解法1:HashSet

使用HashSet,HashSet的时间复杂度O(1),整体时间复杂度O(n),占用空间O(n)。

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param numbers int整型一维数组
     * @return int整型
     */
    public int duplicate(int[] numbers) {
        // write code here
        if(numbers == null || numbers.length == 0){
            return -1;
        }
        HashSet<Integer> container = new HashSet<>();
        for (int n : numbers) {
            if (container.contains(n)) return n;
            container.add(n);
        }
        return -1;
    }
}

3.解法2:用数组替换HashSet

数组的下标查找时间复杂度O(1),整体时间复杂度O(n),占用空间O(n)。

public class Solution2 {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param numbers int整型一维数组
     * @return int整型
     */
    public int duplicate(int[] numbers) {
        // write code here
        if(numbers == null || numbers.length == 0){
            return -1;
        }
        int[] containers = new int[numbers.length];
        for(int n:numbers){
            containers[n] += 1;
            if(containers[n]>1) return n;
        }
        return -1;
    }
}

4.解法3:原地交换

原地交换,如果发现坑位被占用,则说明冲突。

public class Solution3 {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param numbers int整型一维数组
     * @return int整型
     */
    public int duplicate(int[] numbers) {
        // write code here
        if(numbers == null || numbers.length == 0){
            return -1;
        }
        for (int i = 0; i < numbers.length; i++) {
            int a = numbers[i];
            if(a!=i) {
                if(numbers[a]==a) return a;
                swap(a,i,numbers);
            }
        }
        return -1;
    }

    public void swap(int a,int i,int[] numbers) {
        int temp  = numbers[a];
        numbers[a] = numbers[i];
        numbers[i] = temp;
    }
}

总结

通过HashSet可以简化查找复杂度。也可以原地,节省空间。
算法系列在github上有一个开源项目,主要是本系列博客的demo代码。https://github.com/forestnlp/alg
如果您对软件开发、机器学习、深度学习有兴趣请关注本博客,将持续推出Java、软件架构、深度学习相关专栏。
您的支持是对我最大的鼓励。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悟空学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值