Leetcode 540. Single Element in a Sorted Array
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.
You must implement a solution with a logarithmic runtime complexity.
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:
To achieve a logarithmic runtime complexity, we can utilize a binary search approach. The main insight is that if we observe the paired elements, we can determine the side on which the single element lies:
mid
is even and nums[mid] == nums[mid+1]
OR if mid
is odd and nums[mid] == nums[mid-1]
, then the single element is toward the right.Using this strategy, we can adjust our binary search bounds until we zero in on the single element.
Here is the C++ code to solve the problem using binary search:
#include <vector>
using namespace std;
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (mid % 2 == 1) mid--; // Ensure mid is even
if (nums[mid] == nums[mid + 1]) {
left = mid + 2; // Move right
} else {
right = mid; // Move left
}
}
return nums[left];
}
};
The time complexity for the binary search solution is:
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?