找出数组中重复的数字。
在一个长度为 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
swift解法:
class Solution {
func findRepeatNumber(_ nums: [Int]) -> Int {
//方法1 dictionary
// var dic = [Int:Bool]()
// for i in 0..<nums.count{
// if let isExist:Bool = dic[nums[i]] as? Bool, isExist == true{
// return nums[i]
// }
// dic[nums[i]] = true
// }
// return -1
//方法2 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内
var arr = nums
for i in 0..<arr.count{
if i == arr[i]{
continue
}
if arr[i] == arr[arr[i]]{
return arr[arr[i]]
}else{
///交换当前下标index 对应的元素到和元素相等的下标位置; 关键点 下标和值是相等的即hash 函数以元素的值作为hash的key
let temp = arr[i] // 2 = a[0]
arr[i] = arr[temp] // a[0] = a[2] = 1
arr[temp] = temp //a[2] = 2
}
}
return -1
}
}