# 哈希表 classSolution: deffindRepeatNumber(self, nums: List[int]) -> int: dic = {} for num in nums: if num notin dic: dic[num] = 1 else: return num
# 交换位置 classSolution: deffindRepeatNumber(self, nums: List[int]) -> int: i = 0 while i < len(nums): if i == nums[i]: i += 1 continue if nums[nums[i]] == nums[i]: return nums[i] nums[nums[i]],nums[i] = nums[i], nums[nums[i]]
classSolution: defsearch(self, nums: List[int], target: int) -> int: # 解法1 hash = {} for num in nums: if num notinhash: hash[num] = 1 else: hash[num] += 1 returnhash.get(target, 0)
# 解法2 sum = 0 for num in nums: if num == target: sum += 1 returnsum
# 解法3 双指针法 left, right = 0, len(nums) - 1 while left <= right: if nums[left] > target or nums[right] < target: return0 if nums[left] < target: left += 1 if nums[right] > target: right -= 1 if nums[left] == target and nums[right] == target: return right - left + 1 return0
# 解法4 二分法 # 搜索右边界 right i, j = 0, len(nums) - 1 while i <= j: m = (i + j) // 2 if nums[m] <= target: i = m + 1 else: j = m - 1 right = i
if j >= 0and nums[j] != target: return0 # 搜索左边界 left
i = 0 while i <= j: m = (i + j) // 2 if nums[m] < target: i = m + 1 else: j = m - 1 left = j return right - left - 1