Advertisement
hoangreal

Find guaranteed single element in duplicated sorted array

Oct 18th, 2024
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | Source Code | 0 0
  1. """
  2. You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
  3.  
  4. Return the single element that appears only once.
  5. """
  6. class Solution:
  7.     def singleNonDuplicate(self, nums: List[int]) -> int:
  8.         left, right = 0, len(nums)-1
  9.  
  10.         while left < right:
  11.             mid = left + (right - left) // 2
  12.  
  13.             """
  14.            Assuming there is no odd-one-out-element e.g [1,1,2,2,3,3],
  15.            if mid = 0 -> its duplicate is at mid = mid + 1
  16.            if mid = 1 -> its duplicate is at mid = mid - 1
  17.            """
  18.             if ( (mid % 2 == 1 and nums[mid - 1] == nums[mid]) or
  19.                  (mid % 2 == 0 and nums[mid] == nums[mid + 1]) ):
  20.  
  21.                 left = mid + 1
  22.             else:
  23.                 right = mid
  24.  
  25.         return nums[left]
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement