540 Single Element in a Sorted Array 有序数组中的单一元素
给定一个只包含整数的有序数组,每个元素都会出现两次,唯有一个数只会出现一次,找出这个数。
示例 1:
输入: [1,1,2,3,3,4,4,8,8]
输出: 2
示例 2:
输入: [3,3,7,7,10,11,11]
输出: 10
注意: 您的方案应该在 O(log n)时间复杂度和 O(1)空间复杂度中运行。
详见:https://leetcode.com/problems/single-element-in-a-sorted-array/description/
C++:
方法一:
class Solution { public: int singleNonDuplicate(vector<int>& nums) { int res=0; for(int num:nums) { res^=num; } return res; } };
方法二:
class Solution { public: int singleNonDuplicate(vector<int>& nums) { int left = 0, right = nums.size() - 1, n = nums.size(); while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] == nums[mid + 1]) { if ((n - 1 - mid) % 2 == 1) { right = mid; } else { left = mid + 1; } } else { if (mid == 0 || nums[mid] != nums[mid - 1]) { return nums[mid]; } if ((n - 1 - mid) % 2 == 0) { right = mid; } else { left = mid + 1; } } } return nums[left]; } };
参考:http://www.cnblogs.com/grandyang/p/7679036.html