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.
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(object):
def singleNonDuplicate(self, nums):
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = int((lo + hi) / 2)
if nums[mid] == nums[mid ^ 1]:
lo = mid + 1
else:
hi = mid
return nums[lo]
二分查找(Binary Search)
从数组递增有序和O(log n)时间复杂度推断,题目可以采用二分查找求解。
class Solution(object):
def singleNonDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lo, hi = 0, len(nums) - 1
while lo < hi:
mi = (lo + hi) >> 1
if nums[mi] == nums[mi - 1]:
if (mi - 1) & 1:
hi = mi - 2
else:
lo = mi + 1
elif nums[mi] == nums[mi + 1]:
if (mi + 1) & 1:
lo = mi + 2
else:
hi = mi - 1
else:
return nums[mi]
return nums[lo]
出处:http://bookshadow.com/weblog/2017/03/11/leetcode-single-element-in-a-sorted-array/
来自为知笔记(Wiz)