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;
        }
    };
    

      

  • 相关阅读:
    Delphi Excel 操作大全
    ThreadLocal类
    MyBatis实战总结
    MyBatis入门
    Mybatis逆向工程
    2020年全国高校计算机能力挑战赛初赛java组
    集合论基础
    命题与逻辑
    Redis技术概述
    UML图中6种箭头的含义
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3627080.html
Copyright © 2011-2022 走看看