1:题目
title:面试题03 数组中重复的数字
introduction:
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。
数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:
2 <= n <= 100000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
2:python实现
2.1:思路1
2.1.1:代码
from typing import List
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
nums.sort()
x = 0
for i in range(len(nums)):
if nums[i] == nums[i+1]:
x = nums[i]
break
return x
if __name__ == '__main__':
n = [2, 3, 1, 0, 2, 5, 3]
a = Solution()
x = a.findRepeatNumber(n)
print(x)
2.1.2:分析
先对list进行排序。
比如:2,3,1,0,2,5,3,排序后为:0,1,2,2,3,3,5
这样重复的数字经过排序后会连在一起,通过for循环只要找到第一个和他的下一个数字相同的数字,直接返回就是所得
3:c语言实现
3.1:思路1
3.1.1:代码
```c
int findRepeatNumber(int* nums, int numsSize){
int temp;
int a;
for(int i=0; i<numsSize; i++){
a = nums[i];
while(i!=a) {
if (a == nums[a]) {
return a;
}
temp = a;
nums[i] = nums[a];
nums[a] = temp;
}
}
return -1;
}
3.1.2:分析
此思路有点类似哈希表,因为题中规定了数值是0~n-1,所以我们可以让数组第i个索引第位置存储值为i的数,重复的数字会在同一个位置存储的时候出现冲突。首先判断i位置的值nums[i]是否等于i,如果不想等,则找到nums[i]应该所在的索引位置,交换找到的位置和所以i位置的数值,直到i与nums[i]相等。其中,在进行交换的过程中,如果发现nums[i]与找到的索引值相等(即索引值为nums[i]位置已经符合我们的要求),则找到我们要的重复的值,直接return返回。
4:知识点整理
(1)python的sort()函数。
(2)python的typing模块
(3)哈希表