Description,
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.
Binary Search
O(logn), so it must be a binary search solution.
Let’s think of the following case,
[1, 1, 2, 2, 3, 3, 4, 8, 8, 9, 9, 10, 10]
We can treat it pair-wise, like below,
[1, 1, 2, 2, 3, 3, 4, 8, 8, 9, 9, 10, 10]
--0-- --1- --2- --3- --4- --5-- -6-
Then apply binary search on these pairs.
For example, if the mid index is a pair formed by the same number, like [3, 3], we move lo to mid+1.
If the mid index is a pair formed by different number, we move hi to mid. (not mid-1).
Time complexity: O(logn)
public class Solution {
/**
* @timeComplexity: O(logn)
* @solution: Binary Search
* @runtime: 1ms
*/
public int singleNonDuplicate(int[] nums) {
int lo = 0;
int hi = nums.length/2;
int mid = 0;
while (lo < hi) {
mid = (hi+lo)/2; // to avoid overflow
if (nums[2*mid] == nums[2*mid+1]) { // means the "not same pairs" are to its right
lo = mid + 1;
} else {
hi = mid;
}
}
return nums[2*lo];
}
}
Runtime: 1ms