Skip to content

Latest commit

 

History

History

540

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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

Return the single element that appears only once.

Your solution must run in O(log n) time and O(1) space.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 105

Companies:
Amazon, Microsoft, Facebook, Google, Adobe

Related Topics:
Array, Binary Search

Solution 1. Binary Search

// OJ: https://leetcode.com/problems/single-element-in-a-sorted-array/
// Author: github.com/lzl124631x
// Time: O(logN)
// Space: O(1)
class Solution {
public:
    int singleNonDuplicate(vector<int>& A) {
        int L = 0, R = A.size() - 1;
        while (L < R) {
            int M = (L + R) / 2;
            if ((M % 2 == 0 && A[M] == A[M + 1])
               || (M % 2 == 1 && A[M] == A[M - 1])) L = M + 1;
                else R = M;
        }
        return A[L];
    }
};

Solution 2. Binary Search on Even Indices Only

We make sure the M is always even number. Then we check whether A[M] == A[M + 1].

  • If equal, L = M + 2. (Example: 1 1 [2] 2 3, or 1 1 [2] 2 3 3 4)
  • otherwise, R = M. (Example: 1 2 [2] 3 3, or 1 2 [2] 3 3 4 4, or 1 1 [2] 3 3)
// OJ: https://leetcode.com/problems/single-element-in-a-sorted-array/
// Author: github.com/lzl124631x
// Time: O(logN)
// Space: O(1)
class Solution {
public:
    int singleNonDuplicate(vector<int>& A) {
        int L = 0, R = A.size() - 1;
        while (L < R) {
            int M = (L + R) / 2;
            if (M % 2) M--;
            if (A[M] == A[M + 1]) L = M + 2;
            else R = M;
        }
        return A[L];
    }
};

Solution 3. Binary Search

// OJ: https://leetcode.com/problems/single-element-in-a-sorted-array/
// Author: github.com/lzl124631x
// Time: O(logN)
// Space: O(1)
class Solution {
public:
    int singleNonDuplicate(vector<int>& A) {
        int N = A.size(), L = 0, R = N - 1;
        auto valid = [&](int M) { // returns `true` is the index of the single element < M
            return M % 2 ? (M + 1 < N && A[M] == A[M + 1]) : (M - 1 >= 0 && A[M] == A[M - 1]);
        };
        while (L <= R) {
            int M = (L + R) / 2;
            if (valid(M)) R = M - 1;
            else L = M + 1;
        }
        return A[R];
    }
};