题目连接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
初次思考:
题目给了数组的数的范围,在0~n-1
之内,这说明可以使用数组作为数组的下标,所以可以申请一个新的统计数组,该数组的长度和输入数组一样,以原数组中的数的值为统计数组的下标,统计每个数的个数,最后返回数量大于一的数即可。
方法缺陷就是总觉得有点累赘,比如遍历了两边,最后一句的返回值有点辣眼睛。
class Solution {
public int findRepeatNumber(int[] nums) {
int[] counters = new int[nums.length];
for (int i = 0; i < nums.length; i++){
counters[nums[i]]++;
}
for (int i = 0; i < nums.length; i++){
if (counters[i] > 1){
return i;
}
}
return -1;
}
}
改变一下思路
总觉得可以在原来的数组上做点文章:
在原来数组的基础上,对数值和数组下标进行一一对应映射。如果出现遍历处的值已存在就直接返回。推测该方法比上述时间快是因为continue
处减少了遍历次数。
class Solution {
public int findRepeatNumber(int[] nums) {
int len = nums.length;
int i = 0;
while (i < len){
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;
}
}