题目
代码
执行用时:36 ms, 在所有 Python3 提交中击败了61.69% 的用户
内存消耗:16.4 MB, 在所有 Python3 提交中击败了5.18% 的用户
通过测试用例:88 / 88
class Solution:
def findRepeatNumber(self, nums: [int]) -> int:
i = 0
while i < len(nums):
if nums[i] == i:
i += 1
continue
if nums[nums[i]] == nums[i]: return nums[i]
nums[nums[i]], nums[i] = nums[i], nums[nums[i]]
return -1
【方法2】
执行用时:28 ms, 在所有 Python3 提交中击败了94.90% 的用户
内存消耗:16.3 MB, 在所有 Python3 提交中击败了6.79% 的用户
通过测试用例:88 / 88
class Solution:
def search(self, nums: List[int], target: int) -> int:
return Counter(nums)[target]
【方法3】
执行用时:40 ms, 在所有 Python3 提交中击败了32.90% 的用户
内存消耗:16 MB, 在所有 Python3 提交中击败了32.76% 的用户
通过测试用例:88 / 88
class Solution:
def search(self, nums: [int], target: int) -> int:
# 搜索右边界 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
# 若数组中无 target ,则提前返回
if j >= 0 and nums[j] != target: return 0
# 搜索左边界 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