Question
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?
本题难度Easy。
异或法
【复杂度】
时间 O(N) 空间 O(1)
【思路】
利用异或的特性。任何数异或0,得到这个数本身,所以选用0为初始数;任何数n
异或某个数两次,得到仍为n
。所以我们把所有数异或一遍,结果就是出现一次的数。
【代码】
public class Solution {
public int singleNumber(int[] nums) {
//require
int size=nums.length;
int ans=0;
//invariant
for(int num:nums)
ans^=num;
//ensure
return ans;
}
}