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?

    分析:找出数组里面的仅出现一次的数字(其余全部出现三次)。

    可以将所有数字的二进制码都按位进行数字相加,得到每个位上1和0出现的次数,然后在每个位上对3取余。

    例如:   1 1 1 1 0 0 0 1

               0 1 0 1 0 1 0 1 

               1 0 1 0 1 1 0 1

    按位相加:2 2 2 2 1 2 0 3

    取余:      2 2 2 2 1 2 0 0

    运行时间:19ms

     1 class Solution {
     2 public:
     3     int singleNumber(vector<int>& nums) {
     4         const int len = sizeof(int) * 8;
     5         int times[len] = {0};
     6         int result = 0;
     7         
     8         for(int i = 0; i < len; i++){
     9             for(int j = 0; j < nums.size(); j++){
    10                 times[i] += (nums[j] >> i) & 1;
    11             }
    12             result += (times[i] % 3) << i;
    13         }
    14         return result;
    15     }
    16 };
  • 相关阅读:
    安装 Android 运行环境
    Sea.js
    css hack 兼容性
    solr全文检索基本原理
    Solr初步学习
    jquery中ajax的用法
    Javascript的模块化编程
    html 标签
    CSS盒子模型
    python 初学03 Eric+PyQt+python IDE与界面程序
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4508773.html
Copyright © 2011-2022 走看看