Leetcode 136. Single Number
Description:
Given an array of integers, every element appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Thinking:
Knowing that A XOR A = 0 and the XOR operator is commutative, the solution will be very straightforward.
Complexity:
The time complexity is O(n).
Step:
- check whether input is valid.
- Do a for loop and use XOR.
Code:
public class Solution {
public int singleNumber(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int result = 0;
for(int i = 0; i < nums.length; i++){
result^= nums[i];
}
return result;
}
}
Conclusion:
we have to know the bitwise XOR in java 0 ^ N = N
,N ^ N = 0
.