1. 题目
2. 题目描述
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]输出:2 或 3
限制:
2 <= n <= 100000
3. 题解
3.1 题解
3.1 分析
- 定义一个集合
set来存放数组中出现过但不重复的数组; - 然后对数组中的元素进行判断,若
set中不含有,则加入set; - 若
set中已有该元素,则说明该元素是数组中重复出现的元素; - 打印该元素即可;
- 主要是对数组进行遍历操作,所以时间复杂度为
#card=math&code=O%28n%29&id=xNvoh);
3.2 代码
public int findRepeatNumber(int[] nums) {Set<Integer> set = new HashSet<>();int resutl = 0;set.add(nums[0]);for (int i = 1; i < nums.length; i++) {if (set.contains(nums[i])) {resutl = nums[i];} else {set.add(nums[i]);}}return resutl;}
