Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8] Output: 2
Example 2:
Input: [3,3,7,7,10,11,11] Output: 10
Note: Your solution should run in O(log n) time and O(1) space.
因为题目要求是O(logn)了,那么肯定是想到用binary search
这个问题有一个需要注意的地方就是如果一个序列都是俩俩重复
比如 1 1 2 2 3 3。。那么第0位和第1位元素一定是相同的 也就是2m 和2m+1位
但是如果一旦出现一个不重复的 后面的序号关系就全部变了
public class Solution {
public int singleNonDuplicate(int[] nums) {
int low = 0;
int high = nums.length / 2;
while(low < high){
int mid = low + (high - low) / 2;
if(nums[2 * mid] != nums[2 * mid + 1]){
high = mid;
}else{
low = mid + 1;
}
}
return nums[2 * low];
}
}