540. Single Element in a Sorted Array
- Total Accepted: 1638
- Total Submissions: 2985
- Difficulty: Medium
- Contributors: rajaditya
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.
思路:二分查找,由于总元素个数为奇数个,可以将数组分为左右两部分,然后答案在奇数子数组中
#include <iostream>
#include <vector>
using namespace std;
int singleNonDuplicate(vector<int>& nums)
{
if(nums.size() == 1)
return nums[0];
if(nums[0] != nums[1])
return nums[0];
if(nums[nums.size()-1] != nums[nums.size()-2])
return nums[nums.size()-1];
//Binary Search
int l = 0, r = nums.size()-1;
while(l <= r)//"=" is must......
{
int mid = (l+r)/2;
if(nums[mid]!=nums[mid-1] && nums[mid]!=nums[mid+1])
return nums[mid];
if(nums[mid] == nums[mid+1])//change the array to two parts:[l,mid-1]&&[mid+2,r];
{
if((mid-l) % 2 == 1)
r = mid-1;
else
l = mid+2;
}
else if(nums[mid] == nums[mid-1])
{
if((mid-l-1) % 2 == 1)
r = mid-2;
else
l = mid+1;
}
}
/*
if(nums[0] != nums[1])
{
return nums[0];
}
else if(nums[nums.size()-1] != nums[nums.size()-2])
{
return nums[nums.size()-1];
}
else
{
for(int i=1;i<nums.size();i++)
{
if(nums[i]!=nums[i-1] && nums[i]!=nums[i+1])
{
return nums[i];
}
}
}*/
return -1;
}
int main()
{
int t;
vector<int> v;
while(cin>>t)
v.push_back(t);
cout<<singleNonDuplicate(v)<<endl;
return 0;
}