剑指Offer - 01_数组中重复的数字

题目描述

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

示例

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

思路

  1. 数组校验,校验不通过直接抛出一样
  2. 定义Set用来存储数组已经遍历过得数字,为numberSet
  3. 遍历数组,如果numberSet中包含当前数字,直接return当前数字,否则添加当前数字到numberSet
  4. 如果遍历结束,还没return,那抛出异常表示数组中没有重复的数据

Code

public class Solution {
    if (null == nums || 0 == nums.length) {
            throw new IllegalArgumentException("数组为空");
        }
        Set<Integer> numberSet = new HashSet<>();
        for (int num : nums) {
            if (numberSet.contains(num)) {
                return num;
            }
            numberSet.add(num);
        }
        throw new IllegalArgumentException("没有重复数字");
}
posted @ 2021-05-16 18:19  芝諾de乌龟  阅读(37)  评论(0编辑  收藏  举报