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

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:遍历数组

image-20200619204546011

代码

 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;
    }
posted @ 2020-06-25 15:29  北鼻coder  阅读(140)  评论(0编辑  收藏  举报