540. Single Element in a Sorted Array

https://leetcode.com/problems/single-element-in-a-sorted-array/

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.

Example 1:

Input: [1,1,2,3,3,4,4,8,8]
Output: 2

Example 2:

Input: [3,3,7,7,10,11,11]
Output: 10

排好序的数组有一个数出现一次,其它出现两次,找出现一次的数。没排序的话用XOR耗时O(N);排好序后满足从所求的数开始个数变为奇数,之前都是偶数=>二分。mid落点分为奇数和偶数两种情况,当index是偶数时,当和它下一个元素相等时,说明mid和它前面元素数目也是偶数,前半边不存在单个元素,start移到mid后;index是奇数时,--让其变成偶数。

/*
 * @lc app=leetcode id=540 lang=cpp
 *
 * [540] Single Element in a Sorted Array
 */

// @lc code=start
class Solution {
public:
    int singleNonDuplicate(vector<int>& nums) {
        int start = 0, end = nums.size() - 1;
        while (start < end) {
            int mid = start + (end - start) / 2;
            if (mid & 1) mid--;
            if (nums[mid] == nums[mid + 1]) start = mid + 2;
            else end = mid;
        } 
        return nums[start];
    }
};
// @lc code=end

Last updated