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.
//--- C++ ---
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int l=0, r=nums.size();
int mid = 0;
while (l+1<r) {
mid = (l+r)>>1;
if (nums[mid]==nums[mid^0x01])
l = mid+1;
else
r = mid;
}
return nums[l];
}
};
//--- Python ---
class Solution(object):
def singleNonDuplicate(self, nums):
lo, hi=0, len(nums)-1
while lo<hi:
m = (lo+hi)/2
if nums[m]==nums[m^1]:
lo = m+1
else:
hi = m
return nums[lo]
No comments:
Post a Comment