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.
有序,连续,考虑二分法,时间是LOGN,注意这里的判断条件要复杂一点,应该是根据坐标的奇偶性和相等元素位于前还是后来判断取左侧还是右侧。
class Solution {
public int singleNonDuplicate(int[] nums) {
if(nums.length==1)return nums[0];
int lo = 0 ;
int hi = nums.length-1;
int result = 0;
while(lo<=hi)
{
int mid = lo+(hi-lo)/2;
if(mid!=lo&&mid!=hi)
{
if(nums[mid]!=nums[mid-1]&&nums[mid]!=nums[mid+1])
{
result=nums[mid];
break;
}
else if(nums[mid]==nums[mid-1])
{
if((mid&1)==1)
lo=mid+1;
else
hi=mid-2;
}
else
{
if((mid&1)==0)
lo=mid+2;
else
hi=mid-1;
}
}
else
{
if(lo==hi)
{
result=nums[mid];
break;
}
}
}
return result;
}
}