话不多说看代码:
其实刚开始自己想着用一个新数组来做的,但感觉太耗时间,然后看了下提示就知道了。
Given a non-empty 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?
class Solution {
public int singleNumber(int[] nums) {
int s;
if(nums.length==1){
return s=nums[0];
}
int result = 0;//在这里用到的是异或操作的性质:a⊕b⊕a = b
for (int i = 0; i < nums.length; i++) {
result ^= nums[i];//异或就是将数组中每个数字相互异或,最后异或的结果就是单着的那个数
}
return result;
}
}