540. Single Element in a Sorted Array
Given a sorted array consisting of only integers where every element appears exactly twice except for one element which appears exactly 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.
方法1: binary search
discussion: https://leetcode.com/problems/single-element-in-a-sorted-array/discuss/100754/Java-Binary-Search-short-(7l)-O(log(n))-w-explanations
discussion:https://leetcode.com/problems/single-element-in-a-sorted-array/discuss/100766/C%2B%2B-binary-search
思路:
由于题目限制了要在O(log n) 的时间内找到,那么基本只能用binary search。但是如何在看到mid 之后决定向那个方向继续搜索呢?举个栗子:
偶数:
// Index: 0 1 2 3 4 5 6
// Array: 1 1 2 3 3 8 8
// Array: 1 1 3 3 4 8 8
^
奇数:
// Index: 0 1 2 3 4 5 6 7 8
// Array: 1 1 2 3 3 4 4 8 8
// Array: 1 1 2 2 3 3 4 8 8
^
当mid是偶数的时候,左边截取到偶数个数字,右边奇数个。此时我们判断mid–之后是否和右边的能组成pair。如果single在左边,此时刚好是pair,如果在右边则不是。而如果mid是奇数,我们不用将mid–直接和右边比较能否pair。如果能,说明single在右边,如果不能则说明在左边。
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int n = nums.size(), left = 0, right = n - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (mid % 2 == 0) {
if (nums[mid] == nums[mid-1]) right = mid - 2;
else if (nums[mid] == nums[mid+1]) left = mid + 2;
else return nums[mid];
}
else {
if (nums[mid] == nums[mid-1]) left = mid + 1;
else if (nums[mid] == nums[mid+1]) right = mid - 1;
}
}
return nums[left];
}
};
discussion里的另一种高分解法。将两种情况用一个判断句mid–合并。
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int n = nums.size(), left = 0, right = n - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (mid % 2 == 1) mid--;
if (nums[mid] == nums[mid + 1]) left = mid + 2;
else right = mid;
}
return nums[left];
}
};