[Python手撕]有序陣列中的單一元素

Duancf發表於2024-10-15
class Solution:
    def singleNonDuplicate(self, nums: List[int]) -> int:

        left = 0
        right = len(nums)-1
        res = -1
        while left <= right:
            mid = (left+right)//2

            if mid %2 == 0 and nums[mid] != nums[mid-1]:
                res = mid
                left = mid + 1  
            elif mid %2 == 1 and nums[mid] == nums[mid-1]:
                left = mid + 1
            elif mid %2 == 0 and nums[mid] == nums[mid-1]:
                right = mid - 1
            elif mid %2 == 1 and nums[mid] != nums[mid-1]:
                right = mid -1

        
        return nums[res]

相關文章