zoukankan      html  css  js  c++  java
  • 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?

    本题最好理解版本

    有的数字出现3次,个别出现1次,因此每出现3次就可以归零了。

    我们用三个量分别记录出现1次、2次、3次(其实就是0次)的位,分别为x1,x2,x3.

    某一位出现1次,可能之前出现过1次此次的数该位没出现,或者之前出现过3次,该次的数也出现过一次。

    某一位出现2次,可能之前出现过1次此次的数该位出现1次,或者之前出现过2次,该次的数未出现。

    某一位出现3次,可能之前出现过3次此次的数该位没出现,或者之前出现过2次,该次的数也出现过一次。

    由于针对每个位出现几次是要按顺序计算的,一定要注意每次运算时必须用上次的量。

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            if(A == NULL)return 0 ;
            int x0 = ~0;
            int x1 = 0;
            int x2 = 0;
            for(int i = 0 ; i < n;i++)
            {
                int t = x2;
                x2 = (x1 & A[i]) |(x2 & ~A[i]);
                x1 = (x0 & A[i]) |(x1 & ~A[i]);
                x0 = (t & A[i]) |(x0 & ~A[i]);
            }
            return x1;
        }
    };
    

      

  • 相关阅读:
    绘制程序流程图笔记
    强软弱虚引用
    安全点和安全区域
    垃圾回收算法
    垃圾回收相关算法
    内存访问全过程
    多级页表与快表
    分页
    虚拟内存
    内存分段机制
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3627080.html
Copyright © 2011-2022 走看看