题意描述:
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
2 <= n <= 100000
示例:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
解题思路:
Alice: 可以直接用集合 set
如果集合中已经有某个元素就可以直接返回了。
Bob: 而且集合的查找时间还是O(1)
,那最坏情况下整体的时间复杂度也就是O(n)
了。
Alice: 还可以排序,然后查看相邻的元素是不是重复。
Bob: 对,还可以直接统计每个元素出现的次数,因为数字的范围是在0~n-1
的,直接把数组的下标和值当成key
和value
,也是O(n)
的时间复杂度。
Alice: 那这个和集合的做法差不多啊,直接用Python里面的字典也是一样的。😎😎
代码:
Python 方法一: 使用集合 set
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
tmp = set()
for x in nums:
if x in tmp:
return x
else:
tmp.add(x)
return -1
Python 方法二:排序 + 检查相邻元素
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
nums.sort()
for x in range(len(nums)-1):
if nums[x] == nums[x + 1]:
return nums[x]
return -1
Python 方法三: 统计元素个数
class Solution(object):
def findRepeatNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
flag = [0 for x in range(len(nums))]
for x in nums:
flag[x] += 1
if flag[x] > 1:
return x
return -1
Java 方法一:HashSet
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> tmp = new HashSet<Integer>();
for(int x : nums){
if(tmp.contains(x)){
return x;
}else{
tmp.add(x);
}
}
return -1;
}
}
Java 方法二: 排序 + 相邻元素
class Solution {
public int findRepeatNumber(int[] nums) {
Arrays.sort(nums);
for(int i=0; i<nums.length-1; ++i){
if(nums[i] == nums[i+1]){
return nums[i];
}
}
return -1;
}
}
Java 方法三: 统计各个元素
class Solution {
public int findRepeatNumber(int[] nums) {
int[] flag = new int[nums.length];
for(int x : nums){
flag[x]++ ;
if(flag[x] > 1){
return x;
}
}
return -1;
}
}
易错点:
🤷♂️
总结: