topic
Given a non-empty array of integers nums
, each element appears twice except for a certain element that appears only once. Find the element that appears only once.
You must design and implement an algorithm of linear time complexity to solve this problem that uses only constant extra space.
Example 1:
Input: nums = [2,2,1] Output: 1
Example 2:
Input: nums = [4,1,2,1,2] Output: 4
Example 3:
Input: nums = [1] Output: 1
hint:
1 <= nums.length <= 3 * 10^4
-3 * 10^4 <= nums[i] <= 3 * 10^4
- Every element appears twice, except for one element that appears only once.
answer
source code
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for (int i = 0; i < nums.length; i++) {
res = res ^ nums[i];
}
return res;
}
}
Summarize
If I hadn't looked at the label of this question, I really couldn't think of the XOR algorithm.
The XOR result of the same two numbers is 0, and the XOR result of any number and 0 is itself, so as long as all the elements in the array are XORed, the final result is the element we are looking for.