首页 > 编程语言 > 详细

[编程题] 数组中重复的数字

时间:2020-06-25 16:49:50      阅读:66      评论:0      收藏:0      [点我收藏+]

3、数组中重复的数字

方法1:简单排序排序思想比较

//方法1:确定临时最小值,后续匹配(类似简单选择排序思想)
    public int findRepeatNumber(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            int temp = nums[i];
            for (int j = i+1; j < nums.length; j++) {
                if (nums[j]==temp){
                    return nums[j];
                }
            }
        }
        return -1;
    }

上述缺点是时间复杂度为O(n2)

方法2:遍历数组

技术分享图片

代码

 public int findRepeatNumber2(int[] nums) {
        HashSet<Integer> set = new HashSet<>();
        int repeat = -1;
        for (int num : nums) {
            if (!set.add(num)){
                repeat = num;
                break;
            }
        }
        return repeat;
    }

[编程题] 数组中重复的数字

原文:https://www.cnblogs.com/jiyongjia/p/13191863.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!