136. Single Number
考点 | 难度 |
---|---|
Array | Easy |
题目
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
重点
- XOR
Bitwise XOR (exclusive or) “^” is an operator in Java that provides the answer ‘1’ if both of the bits in its operands are different, if both of the bits are same then the XOR operator gives the result ‘0’. XOR is a binary operator that is evaluated from left to right. - For loop
答案
public int singleNumber(int[] nums) {
int temp = 0;
for(int i : nums){
temp ^= i;
}
return temp;
}