Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.
找出排好序的列表中只有一个的数值。
初始令左、右指针low, high分别指向0, len(nums) - 1
当low < high时执行循环:
令mid = (low + high) / 2
若nums[mid] == nums[mid - 1]:
数组可以分为[low, mid - 2], [mid + 1, high]两部分,目标元素位于长度为奇数的子数组中。
同理,若nums[mid] == nums[mid + 1]:
数组可以分为[low, mid - 1], [mid + 2, high]两部分,目标元素位于长度为奇数的子数组中。
若nums[mid]与nums[mid - 1], nums[mid + 1]均不相等,则返回nums[mid]
Example 1:
Input: [1,1,2,3,3,4,4,8,8] Output: 2
Example 2:
Input: [3,3,7,7,10,11,11] Output: 10
Note: Your solution should run in O(log n) time and O(1) space.
class Solution:
def singleNonDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
"""
方法一:
num_set = list(set(nums))
for each in num_set:
if nums.count(each) == 1:
return each
"""
"""
方法二:
return sum(set(nums))*2 - sum(nums)
"""
low = 0
high = len(nums)-1
while low < high:
mid = (low + high) // 2
if nums[mid] == nums[mid-1]:
if len(nums[: mid+1]) % 2 == 0:
low = mid + 1
else:
high = mid - 2
elif nums[mid] == nums[mid+1]:
if len(nums[: mid+1]) % 2 == 0:
high = mid - 2
else:
low = mid + 1
else:
return nums[mid]
return nums[low]