给定一个只包含整数的有序数组 nums
,每个元素都会出现两次,唯有一个数只会出现一次,请找出这个唯一的数字。
你设计的解决方案必须满足 O(log n)
时间复杂度和 O(1)
空间复杂度。
示例 1:
输入: nums = [1,1,2,3,3,4,4,8,8]
输出: 2
示例 2:
输入: nums = [3,3,7,7,10,11,11]
输出: 10
提示:
1 <= nums.length <= 105
0 <= nums[i] <= 105
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int singleNonDuplicate(int[] nums) {
int start = 0;
int end = nums.length - 1;
while (start <= end) {
if (start == end) {
return nums[start];
}
int mid = start + (end - start) / 2;
if (nums[mid - 1] == nums[mid]) {
if ((mid + 1) % 2 == 0) {
start = mid + 1;
} else {
end = mid;
}
} else if (nums[mid + 1] == nums[mid]) {
if ((mid + 2) % 2 == 0) {
start = mid + 2;
} else {
end = mid - 1;
}
} else {
return nums[mid];
}
}
return -1;
}
}
//leetcode submit region end(Prohibit modification and deletion)