版权声明:码字不易,转载请注明出处: https://blog.csdn.net/qq_24309981/article/details/90241534
1 描述
Description
Given a sorted array consisting of only integers where every element appears exactly twice except for one element which appears exactly 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.
2 代码
#include <iostream>
#include <vector>
using namespace std;
//方法一
//int singleNonDuplicate(vector<int>& nums) {
// int res = 0;
// for (const auto& num : nums) res ^= num;
// return res;
//}
//方法二
int singleNonDuplicate(vector<int>& nums) {
int res = 0;
if (nums.size() % 2)
{
res = nums[nums.size() - 1];
for (int i = 0; i < nums.size() - 1; i += 2)
{
if (nums[i] ^ nums[i + 1])
{
res = nums[i];
break;
}
}
}
return res;
}
int main()
{
vector<int> nums = { 1,1,2 };
int res = singleNonDuplicate(nums);
cout << res << endl;
system("pause");
return 0;
}
3 解释
方法一:逻辑门异或门,即使非单调递增数组也同样适用;
方法二:只适用于单调递增的数组;