https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
题意
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
题解一:哈希表法
//哈希表法:O(n)时间复杂度 O(n)空间复杂度
class Solution3 {
public int findRepeatNumber(int[] nums) {
Set<Integer> set=new HashSet<>();
for(int i=0;i<nums.length;i++){
if(!set.add(nums[i]))
return nums[i];
}
return -1;
}
}
题解二:数组法
//数组法:O(n)时间复杂度 O(n)空间复杂度
class Solution {
public int findRepeatNumber(int[] nums) {
int len=nums.length;
boolean[] array=new boolean[len];
for(int i=0;i<len;i++){
if(array[nums[i]])
return nums[i];
else
array[nums[i]]=true;
}
return -1;
}
}
题解三:原地置换法
//原地置换法:O(n)时间复杂度 O(1)空间复杂度
class Solution1 {
public int findRepeatNumber(int[] nums) {
int temp;
for(int i=0;i<nums.length;i++){
while (nums[i]!=i){
if(nums[i]==nums[nums[i]]){
return nums[i];
}
temp=nums[i];
nums[i]=nums[temp];
nums[temp]=temp;
}
}
return -1;
}
}
博客围绕 LeetCode 题目,要找出长度为 n 且数字在 0~n - 1 范围内数组中的重复数字。介绍了三种题解方法,分别是哈希表法、数组法和原地置换法,帮助解决不知有几个数字重复及重复次数的问题。
819

被折叠的 条评论
为什么被折叠?



