剑指offer:
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
lintcode:
给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。
样例
给出 [1,2,2,1,3,4,3],返回 4
思路:
1. 使用hashmap,用空间换时间:
剑指offer代码:
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i:array){
if(map.containsKey(i)){
map.remove(i);
}else{
map.put(i,null);
}
}
Set<Integer> set = map.keySet();
Iterator it = set.iterator();
int a = 0;
while(it.hasNext()){
if(a==0){
num1[0] = (Integer)it.next();
a++;
}else{
num2[0] = (Integer)it.next();
}
}
}
2.
2.1 一个落单的数,其他数出现两次
先从lintcode上的这道题入手,题中除一个数以外其他数均出现了两次。首先我们知道,相同的两个数异或结果是为0的,所以对于lintcode这一道题,我们将所有的数取异或,自然最后的结果就是落单的那个数了。
代码:
public int singleNumber(int[] A) {
// write your code here
int num = 0;
for (int i = 0; i < A.length; i++) {
num ^= A[i];
}
return num;
}
2.2 两个落单的数,其他数出现两次
遇到这种情况,我们先设想下按照上面的方法照做会出现什么:将全部的数异或,最终的结果必然是那两个落单的数异或的结果(这两个数不一样,题目交代)。也就是说在这个结果数字的二进制表示中至少就有一位为1 。我们在结果数字中找到第一个为1 的位的位置,记为第N 位。现在我们以第N 位是不是1 为标准把原数组中的数字分成两个子数组,第一个子数组中每个数字的第N 位都为1 ,而第二个子数组的每个数字的第N 位都为0 。
现在我们已经把原数组分成了两个子数组,每个子数组都包含一个只出现一次的数字,而其它数字都出现了两次。因此到此为止,所有的问题我们都已经解决。
代码:
public void singleNumber(int [] array,int num1[] , int num2[]){
if(array==null || array.length <=1){
num1[0] = 0;
num2[0] = 0;
return;
}
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum ^= array[i]; // 所有数的异或
}
int index=0;
for (; index < 32; index++) {
if((sum & (1<<index))!=0){break;} // 32位, 求出第一个不为0的位置N
}
for (int i = 0; i < array.length; i++) {
if((array[i] & (1<<index))!=0){
num1[0] ^= array[i]; // 以第N位不为0为标准,划分两个子数组
}else{
num2[0] ^= array[i];
}
}
}
2.3 一个落单的数,但是其他数出现了三次
用一个32位的数的每一位表示某一位出现几次,出现3次就给它归零
public int singleNumberII(int[] A) {
if (A == null || A.length == 0) {
return -1;
}
int result=0;
int[] bits=new int[32];
for (int i = 0; i < 32; i++) {
for(int j = 0; j < A.length; j++) {
bits[i] += A[j] >> i & 1;
bits[i] %= 3;
}
result |= (bits[i] << i);
}
return result;
}