每日一练-leetcode
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入: [2, 3, 1, 0, 2, 5, 3] 输出:2 或 3
方法一:
使用HashSet遇到重复的输出
class Solution {
public int findRepeatNumber(int[] nums) {
if(nums == null||nums.length == 0){
return -1;
}
Set<Integer> dic = new HashSet<>();
for(int num:nums){
if(dic.contains(num)){
return num;
}else{
dic.add(num);
}
}
return -1;
}
}
执行用时: 7 ms
内存消耗: 47.4 MB
方法二:
遍历数组 nums ,设索引初始值为 i = 0:
若 nums[i] = i: 说明此数字已在对应索引位置,无需交换,因此跳过;
若 nums[nums[i]] = nums[i]: 代表索引 nums[i]处和索引 i 处的元素值都为 nums[i],即找到一组重复值,返回此值 nums[i];
否则: 交换索引为 i和 nums[i]的元素值,将此数字交换至对应索引位置。
若遍历完毕尚未返回,则返回 -1。
class Solution {
public int findRepeatNumber(int[] nums) {
int i = 0;
while(i < nums.length) {
if(nums[i] == i) {
i++;
continue;
}
if(nums[nums[i]] == nums[i]) return nums[i];
int tmp = nums[i];
nums[i] = nums[tmp];
nums[tmp] = tmp;
}
return -1;
}
}
执行用时: 0 ms
内存消耗: 46.2 MB
浙公网安备 33010602011771号