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?
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
1. a ^ a = 0
2. a ^ b = b ^ a
3. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c
----> a ^ b ^ a = b
所以把全部数字异或一遍就能找到只出现一次的数 时间O(n)
public class Solution {
public int singleNumber(int[] nums) {
if (nums.length == 0 || nums == null) {
return -1;
}
int res = 0;
for (int i = 0; i < nums.length; i++) {
res = res ^ nums[i];
}
return res;
}
}
没有评论:
发表评论