单独的数字(线性时间复杂度,且无额外空间)

给定一个数组 A,除了一个数出现一次之外,其余数都出现三次。找出出现一次的数。

如:{1, 2, 1, 2, 1, 2, 7},找出 7

难点:算法只能是线性时间的复杂度,并且不能使用额外的空间。

策略:采用位运算,把每个数字的每一位都加起来,对3取余。(同理,其余数出现k次,就对k取余)

本机int型变量是32位,故外层循环为32位(常数级循环),内层n重循环,因此符合线性时间复杂度。

#include 
#include 
using namespace std;

int arrs[500];
int res[32];

int getSingle(int a[], int n){ //n个数
  int temp;
  int sum = 0;
  for(int i = 0; i < 32; ++i){ //常数32轮循环
    temp = 0;
    for(int j = 0; j < n; ++j){
      temp += (a[j]>>i)&1;
    }
    temp = temp % 3;
    res[31-i] = temp;
    // cout << temp << endl;
  }
  for(int i = 31; i >= 0; --i){
    sum += res[i]*pow(2, 31-i); 
  }

  return sum;
}

int main(){
  int n, m;
  cin >> n;
  for(int i = 0; i < n; ++i){
    cin >> m;
    arrs[i] = m;
  }
  cout << getSingle(arrs, n) << endl;
  return 0;
}


你可能感兴趣的:(ACM)