Description:
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.
题意:给定一个已排序的数组,要求找出在数组中仅出现一次的那个元素(其他所有元素均出现两次);
解法:考虑异或操作,对于元素a来说
- a ^ a = 0
- a ^ 0 = a
因此,我们对数组中的所有元素进行异或操作,相同的元素异或得到结果0,而0与数组中仅出现一次的元素再异或得到的就是元素本身;其时间复杂度为O(n);
Java
class Solution {
public int singleNonDuplicate(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
}