540 Single Element in a Sorted Array
1. Question
Input: [1,1,2,3,3,4,4,8,8]
Output: 2Input: [3,3,7,7,10,11,11]
Output: 102. Implementation
3. Time & Space Complexity
Last updated
Input: [1,1,2,3,3,4,4,8,8]
Output: 2Input: [3,3,7,7,10,11,11]
Output: 10Last updated
public class Solution {
public int singleNonDuplicate(int[] nums) {
if (nums == null || nums.length <= 2) {
return -1;
}
int start = 0, end = nums.length - 1, mid = 0;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (nums[mid - 1] == nums[mid]) {
if ((mid - 2 + 1) % 2 != 0) {
end = mid - 2;
}
else {
start = mid + 1;
}
}
else if (nums[mid] == nums[mid + 1]) {
if ((mid - 1 + 1) % 2 != 0) {
end = mid - 1;
}
else {
start = mid + 2;
}
}
else {
return nums[mid];
}
}
if (start > 0 && nums[start - 1] != nums[start]) {
return nums[start];
}
else {
return nums[end];
}
}
}