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?
翻译:
给定一个整数数组,每个元素出现两次除了一个,请找到那一数。
注意:
你的算法运行时应该有一个线性的复杂性。你能实现它不使用额外的内存吗?
解题思路1:
首先分析这个题目发现需要注意,所有的数都会出现2次,除了一个,但是并没有说这个数是出现了几次,所以那个single number出现的次数只是不等于2而已。在没有考虑他的额外要求时,很简单很单纯的就是使用2层for循环对数组中所有数字的出现次数计数,最后判断次数不等于2的就是那个single number。
这个解法太没技术含量,但是能够满足基本要求。
public int singleNumber(int[] nums) {
int len = nums.length;
int count []= new int[len];
for(int i = 0; i < len; i++){
for(int j = 0; j < len; j++){
if(nums[i] == nums[j]){
count[i]++;
}
}
if(count[i] != 2){
return nums[i];
}
}
return 0;
}
具体情况如下:
解题思路2:后面找了别人的代码,发现一个很简单的方法:异或
参考代码的核心思路就是运用了
<两个相同的数进行按位异或运算结果一定为0,一个数与0按位异或结果即为该数本身>,所以讲数组中所有数按位异或,留下的那个数即是那个single number。
public int singleNumber(int[] nums) {
int res = 0;
for(int i = 0; i < nums.length; i++){
res ^= nums[i];
}
return res;
}
具体情况如下:
解题思路3:还有一种类似的:
if (nums == null || nums.length < 1) {
throw new IllegalArgumentException("nums");
}
for (int i = 1; i< nums.length; i++) {
nums[0] ^= nums[i];
}
return nums[0];
具体情况如下: