leetcode 540. Single Element in a Sorted Array
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.
题目大意:一个有序的数列,有一个数出现一次,其他的数出现两次。求这个出现一次的数
思路:二分,首先序列是有序的,所以相邻的两个数要么相等,要么不相等。如果不相等,那会是哪个区间有single num呢 我们再判断区间(r-mid+1)是不是奇数
1.区间mid~r是奇数,并且nums[mid+1]和nums[mid]不等,说明single num出现在l~mid。
2.区间mid~r是偶数,并且nums[mid+1]和nums[mid]相等,说明single num出现在l~mid-1
3.区间mid~r是奇数,并且nums[mid+1]和nums[mid]相等,说明single num出现在mid~r
4.区间mid~r是偶数,并且nums[mid+1]和nums[mid]不等,single num出现在mid~r
代码如下:
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int l = 0;
int r = nums.size()-1;
int mid = 0;
while (l < r) {
mid = (l+r)/2;
if (nums[mid+1] != nums[mid]) mid = mid+1;
if ((r - mid + 1)%2) {
l = mid;
} else {
r = mid - 1;
}
}
return nums[r];
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: