剑指offer03-数组中重复的数字

原题(来源Leetcode)

找出数组中重复的数字。

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

示例 1:

输入:
[2, 3, 1, 0, 2, 5, 3] 输出: 2 或 3

限制:

2 <= n <= 100000

解法

思想

限定了范围,就用bitmap去重的思想

代码

class Solution {
    public int findRepeatNumber(int[] nums) {
        boolean exist[] = new boolean[nums.length];
        for(int i:nums){
            if(exist[i] == true) return i;
            exist[i] = true;
        } 
        return -1;
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/%e5%89%91%e6%8c%87offer03-%e6%95%b0%e7%bb%84%e4%b8%ad%e9%87%8d%e5%a4%8d%e7%9a%84%e6%95%b0%e5%ad%97/

发表回复

登录后才能评论