题目:
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?
分析:
题意是给定一个数组,该数组除了一个元素只出现一次外,其他元素均出现2次,找出这个出现一次的元素。Note中要求具有线性复杂度,也就是O(n)。
本题的考察点是异或运算,解题的关键是利用异或运算的交换律:a ⊕b ⊕ c = a ⊕ (b ⊕ c) = (a ⊕ b) ⊕ c,以及a ⊕ a = 0。对数组的全部元素进行异或运算,将里面出现2次的元素交换到一起,这样由于a ⊕ a = 0,最终结果就是那个只出现一次的元素。
代码实现1(时间复杂度O(n)):
public class Solution {
public int singleNumber(int[] nums) {
int res=0;
for(int i=0;i<nums.length;i++){
res=res^nums[i];
}
return res;
}
}
代码实现2(时间复杂度O(n^2)):
public class Solution {
public int singleNumber(int[] nums) {
int target;
for(int i=0;i<nums.length;i++){
target=nums[i];
boolean found=false;
for(int j=0;j<nums.length;j++){
if(target==nums[j]&&i!=j){
found=true;
break;
}
}
if(found==false){
return target;
}
}
return 0;
}
}