原题链接在这里:https://leetcode.com/problems/single-number/
首先会想到HashMap,HashSet的想法,但会用到extra O(n) space.
所以就要用到bit manipulation,这里和Single Number II非常相似,就不复述了。
但这里有个更快的方法,就是用异或 ^ operator. 异或 every number in the array and the result would be the single number.
Note: 1. 函数返回的是int,corner case 不能返回null,否则会报错。
2. 在写嵌套循环时,注意不要搞混 i , j 的含义。
AC Java:
public class Solution {
public int singleNumber(int[] nums) {
/*Method 1
if(nums == null || nums.length == 0)
return Integer.MIN_VALUE;
HashSet hs = new HashSet();
for(int i = 0; i < nums.length; i++){
if(!hs.contains(nums[i])){
hs.add(nums[i]);
}else{
hs.remove(nums[i]);
}
}
Iterator it = hs.iterator();
int res = Integer.MIN_VALUE;
while(it.hasNext()){
res = (int)it.next();
}
return res;
*/
/*Method 2
if(nums == null || nums.length == 0)
return Integer.MIN_VALUE;
int [] bitCounter = new int[32];
for(int i = 0; i<32; i++){
for(int j = 0; j<nums.length; j++){
bitCounter[i] += (nums[j]>>i&1); //error
}
}
int res = 0;
for(int i = 0; i<32; i++){
res += (bitCounter[i]%2)<<i;
}
return res;
*/
//Method 3
if(nums == null || nums.length == 0)
return Integer.MIN_VALUE;
int res = 0;
for(int j = 0; j < nums.length; j++){
res = res ^ nums[j];
}
return res;
}
}