540. Single Element in a Sorted Array

12 阅读1分钟

image.png

Solution: Binary search

  • We remove nums[mid], resulting in left half arr and right half arr,
    • the subarray containing the single element must be odd-lengthed.
    • The subarray not containing it must be even-lengthed.

There are 4 cases

  • Case 1: Mid’s partner is to the right, and the halves were originally even.

image.png

  • Case 2: Mid’s partner is to the right, and the halves were originally odd

image.png

  • Case 3: Mid’s partner is to the left, and the halves were originally even.

image.png

  • Case 4: Mid’s partner is to the left, and the halves were originally odd.

image.png

class Solution {
    public int singleNonDuplicate(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == nums[mid + 1]) {
                if ((right - mid + 1) % 2 == 0) {
                    right = mid - 1;
                } else {
                    left = mid + 2;
                }
            } else if (nums[mid] == nums[mid - 1]) {
                if ((right - mid + 1) % 2 == 0) {
                    left = mid + 1;
                } else {
                    right = mid - 2;
                }
            } else {
                return nums[mid];
            }
        }
        return nums[left];
    }
}