zoukankan      html  css  js  c++  java
  • [LeetCode] Single Number II

    Given an array of integers, every element appears three times except for one. Find that single one.

    Note:
    Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

    方法一:创建一个长度为 多少个bit/sizeof(int) * 8的数组 count[sizeof(int)*8],count[i] 表示在在 i 位
    出现的 1 的次数。如果 count[i] 是 3 的整数倍,则忽略;否则就把该位取出来组成答案。

     1 class Solution
     2 {
     3     public:
     4         int singleNumber(int A[], int n)
     5         {
     6             vector<int> cnt;
     7             int width = sizeof(int)*8;
     8             cnt.resize(width, 0);
     9             int res = 0;
    10 
    11             for(int i  = 0; i< n; i++)
    12             {
    13                 for(int j  = 0; j< width; j++)
    14                 {
    15                     cnt[j] += (A[i] >> j) & 0x1;
    16                     //cnt[j] %= 3;
    17                 }
    18 
    19             }
    20             for(int j  = 0; j< width; j++)
    21             {
    22                 //cout << "j :	" <<j <<"	 cnt	"<< cnt[j]<<endl;
    23                 if(cnt[j]%3 != 0)
    24                     res ^=  ( 1 << j);
    25             }
    26             return res;
    27         }
    28 } ;
  • 相关阅读:
    rabbitmq入门
    php7.2 安装redis扩展
    php安装扩展的几种方法
    yum安装php7.2
    相关报错
    [枚举]P1089 津津的储蓄计划
    [DFS]排列的生成
    [枚举]P1085 不高兴的津津
    [模拟]P1047 校门外的树
    [模拟]P1046 陶陶摘苹果
  • 原文地址:https://www.cnblogs.com/diegodu/p/3812826.html
Copyright © 2011-2022 走看看