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

15 阅读1分钟

找出数组中重复的数字。


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

示例 1:

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

限制:

2 <= n <= 100000

方法一:还得是优雅的哈希表呢

思路:题目要求我们找重复的,第一时间想到Hashset的特点,只存不重复的元素,那么事情就变得简单了起来

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

来源:力扣(LeetCode)
链接:leetcode.cn/problems/sh…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。