Skip to content

Latest commit

 

History

History
37 lines (27 loc) · 800 Bytes

540.md

File metadata and controls

37 lines (27 loc) · 800 Bytes

540 Single Element in a Sorted Array

Description

link


Solution

  • 注意区分奇数偶数情况,因为中位数是向下取整,有两种情况出现,分别对应左右边界

Code 2

O(log(n))

class Solution:
    def singleNonDuplicate(self, nums: List[int]) -> int:
        l, r = 0, len(nums) - 1
        while(l < r):
            m = (l + r) // 2
            if m % 2 == 0:
                if nums[m] != nums[m + 1]:
                    r = m
                else:
                    l = m + 1
            else:
                if nums[m] != nums[m - 1]:
                    r = m
                else:
                    l = m + 1
                    
        return nums[l]