• 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运算符与表达式
    subShell与代码块
    参数展开与特殊字符
    变量和参数
    shelll Test
    Cypher查询语言--Neo4j 入门 (一)
    那些争议最大的编程观点
    大型网站架构不得不考虑的10个问题
    大型网站架构演变
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3518021.html
Copyright © 2020-2023  润新知