Leetcode

Single Element in a Sorted Array

  • Time:O(\log n)
  • Space:O(1)

C++

class Solution {
 public:
  int singleNonDuplicate(vector<int>& nums) {
    int l = 0;
    int r = nums.size() - 1;

    while (l < r) {
      int m = (l + r) / 2;
      if (m & 1)
        --m;
      if (nums[m] == nums[m + 1])
        l = m + 2;
      else
        r = m;
    }

    return nums[l];
  }
};

JAVA

class Solution {
  public int singleNonDuplicate(int[] nums) {
    int l = 0;
    int r = nums.length - 1;

    while (l < r) {
      int m = (l + r) / 2;
      if (m % 2 == 1)
        --m;
      if (nums[m] == nums[m + 1])
        l = m + 2;
      else
        r = m;
    }

    return nums[l];
  }
}

Python

class Solution:
  def singleNonDuplicate(self, nums: List[int]) -> int:
    l = 0
    r = len(nums) - 1

    while l < r:
      m = (l + r) // 2
      if m % 2 == 1:
        m -= 1
      if nums[m] == nums[m + 1]:
        l = m + 2
      else:
        r = m

    return nums[l]