3. 数组中重复的数字 (findRepeatNumber)
1. python(1)
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
sorted_nums = sorted(nums)
sorted_nums_length = len(sorted_nums)
for i in range(sorted_nums_length):
if sorted_nums[i] == sorted_nums[i-1]:
return sorted_nums[i]
return -1
2. python(2)
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
dic = set()
for num in nums:
if num in dic:
return num
dic.add(num)
return -1
3. Java
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int repeat =-1;
for(int num:nums){
if(!set.add(num)){
repeat = num;
break;
}
}
return repeat;
}
}