一、題目描述
題目一:一個整型數組裏除了1個數字之外,其他的數字都出現了偶數次,找出這個數字,要求時間複雜度O(n),空間複雜度O(1)
題目二:一個整型數組裏除了2個數字之外,其他的數字都出現了偶數次,找出這兩個數字,要求時間複雜度O(n),空間複雜度O(1)
二、解題思路
題目一:異或運算,偶數個一樣的數異或爲0,異或符合交換律,所以只需要把所有數組中所有數字異或一次就可以了
題目二:整體做異或運算,結果必不爲0,且結果數字的二進制表示中至少有一位爲1,找出第一個爲1的位置target_index,以其爲標準將原數組分爲兩個子數組,第一個子數組中每個數字的第target_index位置上的都是1,第二個子數組中每個數字的第target_index位置上的都是0。那麼每個子數組中分別包含一個出現奇數次的數字,分別做異或即可
三、解題算法
1、題目一:找出現奇數次的一個數字
/******************************************************
author:tmw
date:2018-8-7
******************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/** 題目一
* 只有一個數字出現奇數次
**/
void findNumber1AppearOdd(int* array, int array_len)
{
/**入參檢查**/
if( !array || array_len < 2 ) return;
int res = 0;
int i;
for( i=0; i<array_len; i++ )
res = res ^ array[i];
printf("%d\n",res);
}
2、題目二:找出現奇數次的兩個數字
/******************************************************
author:tmw
date:2018-8-7
******************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/**判斷當前數字第target_index位是否爲1**/
bool isBit1( int number, int target_index )
{
number = number >> target_index;
return number&1;
}
/**有兩個數字出現奇數次**/
void findNumbers2AppearOdd(int *array, int array_len)
{
if( array == NULL || array_len < 2 ) return;
/**對整體做異或,得到不爲0的值**/
int excusiveOR_res = 0;
int i;
for( i=0; i<array_len; i++ )
excusiveOR_res = excusiveOR_res^array[i];
/**找到excusiveOR_res中第一個爲1的位置**/
int target_index = 0;
while( excusiveOR_res & 1 == 1 && target_index < 8*sizeof(int) )
{
/**右移1位**/
excusiveOR_res = excusiveOR_res >> 1;
target_index++;
}
/**按照target_index位置上的值是否爲1,將數組分成兩個部分計算,分別得到結果**/
int res1 = 0;
int res2 = 0;
for( i=0; i<array_len; i++ )
{
if( isBit1(array[i], target_index) )
res1 = res1 ^ array[i];
else
res2 = res2 ^ array[i];
}
printf("res1 = %d",res1);
printf("res2 = %d",res2);
}
夢想還是要有的,萬一實現了呢~~~~~ヾ(◍°∇°◍)ノ゙~~~~~~~