Single Element in a Sorted Array LeetCode
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
class Solution {
public int singleNonDuplicate(int[] nums) {
int start = 0;
int end = nums.length - 1;
// Binary search loop - keep narrowing the range until we find the single element
while (start < end) {
// Calculate mid index safely to avoid overflow
int mid = start + (end - start) / 2;
// Check if mid and mid+1 are a pair (same number)
if (nums[mid] == nums[mid + 1]) {
// If the number of elements on the right side (including mid) is even
if ((end - mid) % 2 == 0) {
// That means the single element is on the right side, skip this pair
start = mid + 2;
} else {
// The single element is on the left side
end = mid - 1;
}
} else {
// If mid and mid+1 are NOT a pair, it means either:
// 1. mid is the single element
// 2. the pair is broken here and the single is on the left side
// Check how many elements are on the right side (including mid)
if ((end - mid) % 2 == 0) {
// Even number of elements, so single is on the left side (or at mid)
end = mid;
} else {
// Single element is on the right side
start = mid + 1;
}
}
}
// When start == end, we have found the single element
return nums[end];
}
}
Comments
Post a Comment