• LeetCode


    Single Number II

    2014.1.13 20:25

    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?

    Solution:

      Still, exclusive OR is a wonderful operator.

      This time every number appears 3 times except an extra number. That is to say, every '1' bit appears 3k times if that extra number has '0' on this bit, or 3k+1 times if it has '1' on this bit. If we can use this 3k property, we can separate that extra number from those triads.

      Here we define four variables:

        a1: the bits that have appeared 3k+1 times.

        a2: the bits that have appeared 3k+2 times.

        b: the bits that have (or have not) appeared 3k times.

      The algorithm works in the following process:

        1. initialize all to 0.

        2. for each A[i], update a2 from a1 and A[i].

        3. for each A[i], update a1 from A[i].

        4. for each A[i], update b from a1 and a2.

        5. if a bit appears 3k times, it can't appear 3k+1 or 3k+2 time, thus subtract b from a1 and a2.

      Time complexity is O(n), space complexity is O(1).

    Accepted code:

     1 // 1CE, 1AC, just try to avoid spelling error, OK?
     2 class Solution {
     3 public:
     4     int singleNumber(int A[], int n) {
     5         // IMPORTANT: Please reset any member data you declared, as
     6         // the same Solution instance will be reused for each test case.
     7         if(n <= 0){
     8             return 0;
     9         }
    10         
    11         int i;
    12         int a1, a2;
    13         int b;
    14         
    15         a1 = a2 = b = 0;
    16         for(i = 0; i < n; ++i){
    17             // notice: not a2 = (a1 & A[i]);
    18             // 1CE here, not a[], but A[]
    19             a2 |= (a1 & A[i]);
    20             a1 = (a1 ^ A[i]);
    21             b = ~(a1 & a2);
    22             a1 &= b;
    23             a2 &= b;
    24         }
    25         // all bits of '1' appear for 3k + 1 or 3k times, thus the remaining one is the result.
    26         return a1;
    27     }
    28 };
  • 相关阅读:
    Python自制小时钟,并转换为exe可执行程序详解
    Linux下搭建jmeter
    adb server is out of date. killing完美解决
    Python通过百度Ai识别图片中的文字
    robotframework在3.7下的搭建
    VIVO 手机重力传感器踩坑记录
    GPU 实现 RGB -- YUV 转换 (OpenGL)
    iOS UImage 与 RGB 裸数据的相互转换
    CVPixelBuffer的创建 数据填充 以及数据读取
    glReadPixel 读取数据错误问题
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3518021.html
Copyright © 2020-2023  润新知