原题链接:https://leetcode-cn.com/problems/single-element-in-a-sorted-array/
使用二分查找法,索引是偶数则应后面一个相等,索引为奇数则应与前面一个相等,逐步缩小范围
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int l = 0, h = nums.size() - 1;
while (l < h) {
int m = (h - l) / 2 + l;
if (nums[m] == nums[m ^ 1]) {
l = m + 1;
} else {
h = m;
}
}
return nums[l];
}
};
单一元素的索引必为偶数,于是使用二分查找,逐步缩小范围,直到找到数
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int l = 0, h = nums.size() - 1;
while (l < h) {
int m = (h - l) / 2 + l;
cout << " h is " << h << " l is " << l << " m is " << m << endl;
m -= m & 1;
if (nums[m] == nums[m + 1]) {
l = m + 2;
} else {
h = m;
}
}
return nums[l];
}
};