您的位置:首页 > 其它

leetcode 540. Single Element in a Sorted Array 题解

2017-08-22 20:13 477 查看
原题:

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.

翻译:

给一个有序整数数组,除了一个数,其余数都会出现两次,找到这个数并返回。

(你的程序必须在O(log n)的时间,O(1)的空间内运行完)

思路:

这是一个binary search的题目,找到中点后看这个单一的数在左边还是在右边,每次都能把数组的长度削减一半。

程序:

class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
if(nums.size() % 2 == 0) {
return 0;
}
int low = 0, high = (int)nums.size() - 1;
while(low < high) {
int mid = (low + high)/2;
if(mid % 2 == 0) {
if(nums[mid] == nums[mid + 1]) {
low = mid + 2;
}else {
high = mid - 2;
}
}else {
if(nums[mid] == nums[mid + 1]) {
high = mid - 1;
}else {
low = mid + 1;
}
}
}
return nums[low];
}
};

(如果思路不好或者代码有能改进的地方请留言告诉我,谢谢。)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: