zoukankan      html  css  js  c++  java
  • leetcode 137

    137. 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出现的次数,1出现次数不为3的倍数的位所组成的数即为要找的数。

    代码实现:

     1 class Solution {
     2 public:
     3     int singleNumber(vector<int>& nums) {
     4         int n = nums.size();
     5         int ones = 0;
     6         int twos = 0;
     7         int xthrees = 0;
     8         for(int i = 0; i < n; ++i)
     9         {
    10             twos |= (ones & nums[i]);
    11             ones ^= nums[i];
    12             xthrees = ~(ones & twos);
    13             ones &= xthrees;
    14             twos &= xthrees;
    15         }
    16         return ones;
    17     }
    18 };
  • 相关阅读:
    引用赋值的问题
    mysql的笔记
    输入法失败
    eclipse的快捷键
    c++/c在两个文件公用一个变量
    用c++ sttring检测名字是否有空格
    QLineEdit的信号函数
    c++博客转载
    qt-博客
    QT聊天室--重大bug
  • 原文地址:https://www.cnblogs.com/shellfishsplace/p/5947259.html
Copyright © 2011-2022 走看看