剑指 Offer 03. 数组中重复的数字
难度:⭐⭐
👾题目描述:
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
👩🏫题目解析:
❎自己的第一反应是暴力算法:
class Solution {
public int findRepeatNumber(int[] nums) {
for(int i = 0;i < nums.length;i++){
for(int j = i + 1;j < nums.length;j++){
if(nums[i] == nums[j]){
return nums[i];
}
}
}
return -1;
}
}
🟢利用哈希表来解决这个问题:
核心思想:初始化一个空的集合,然后遍历数组,将数组中的元素依次添加到集合中,如果添加成功则证明该数字不重复,若添加失败则证明集合中已经存在该数字了,即该数字重复,输出即可。
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;
}
}
此题还有很多其他解法,比如排序比较等,可再深入研究。
PS:若内容有错误欢迎留言指正🙇♂️!若内容对您有帮助欢迎点赞👍!