zoukankan      html  css  js  c++  java
  • 137. Single Number II (Bit)

    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?

    思路:用变量分别存储出现一次、两次、三次的number

    出现一次的number: 抑或操作去除了出现两次的可能,与未出现三次的number作“与操作”去除了出现三次的可能

    出现两次的number:与出现一次的number作“与操作”

    出现三次的number: 出现一次的number“与操作”出现两次的number

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int once = 0;  
            int twice = 0;  
      
            for (int i = 0; i < n; i++) {  
                twice |= once & A[i]; //将出现两次1的位,在twice中置1
                once ^= A[i];  //将出现一次1的位,在once中置1,出现两次则置0
                int not_three = ~(once & twice);  //将出现三次1的位,在not_tree中置0
                once = not_three & once;  //将出现三次1的位,在once中置0
                twice = not_three & twice;  //将出现三次1的位,在twice中置0
            }  
            return once;  
        }
    };
  • 相关阅读:
    阅读提问
    阅读笔记
    结对需求分析
    分工
    对软件工程课程的期望
    JAVAWEB-Spring Boot学习
    团队编程-项目作业6-程序维护
    团队-吃货之家-项目总结
    团队编程项目作业5-小组评分
    安装Vue.js之Node.js,NMP环境搭建
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5022845.html
Copyright © 2011-2022 走看看