题目:
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?
我的思路:因为只有一个不同的数,所以只需把这些所有元素异或运算就可以得到其中只有一个的元素。
具体代码如下:
public int singleNumber(int[] nums) {
int result = nums[0];
for(int i = 1; i < nums.length; i++){
result = result^nums[i];
}
return result;
}