540. Single Element in a Sorted Array
Problem Statement
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
Intuition
Approach:
Note that,
When a single element appears ordering of indexes is changes
1 1 2 2 3 4 4
0 1 2 3 4 5 6
Note at odd index, second repeat comes at odd
But then after the single element appears, second repeat comes at even
take advantage of that
Links
https://leetcode.com/problems/single-element-in-a-sorted-array/description/
Video Links
Approach 1:
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
if(nums.size() == 1)
return nums[0];
int low=0, high=nums.size()-1;
while(low<high){
int mid = low+(high-low)/2;
if(mid % 2 != 0){
if(nums[mid] == nums[mid-1])
low = mid+1;
else if(nums[mid] == nums[mid+1])
high= mid-1;
else
return nums[mid];
}
else{
if(nums[mid] == nums[mid+1])
low = mid+2;
else if(nums[mid] == nums[mid-1])
high = mid-2;
else
return nums[mid];
}
}
return nums[low];
}
};
Approach 2:
Approach 3:
Approach 4:
Similar Problems
Last updated