zoukankan      html  css  js  c++  java
  • [LeetCode] Single Number II, Solution

    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?

     

    [Thoughts]

    这个题有类似于single number的解法,即通过位运算,一遍扫描得到结果。还是读书的时候见过,大概是两个变量,相互做异或、补之类的运算,早不记得详情了。

    现在的解法是比较普通的。因为题目已经说了,除了一个数字以外,其他的都出现了3次,如果我们把那个特殊的数剔除,并把剩下的数于每一位来加和的话,每一位上1出现的次数必然都是3的倍数。所以,解法就在这里,将每一位数字分解到32个bit上,统计每一个bit上1出现的次数。最后对于每一个bit上1出现的个数对3取模,剩下的就是结果。

     

    [Code]

    1 int singleNumber(int A[], int n) {
    2 vector<int> bit(32,0);
    3
    4 for(int i =0; i< n; ++i)
    5 {
    6 int k=1;
    7 for(int j =0; j<32; ++j)
    8 {
    9 int rotated;
    10 if((rotated = A[i]>>j) == 0) break;
    11 bit[j] += rotated & k;
    12 }
    13 }
    14
    15 int target=0;
    16 for(int i =0; i<32; ++i)
    17 {
    18 target += (bit[i]%3 <<i);
    19 }
    20 return target;
    21 }
  • 相关阅读:
    IDEA与Eclipse
    解释器模式
    设计模式(十一)—— 策略模式
    设计模式(六)—— 装饰模式
    Java注解
    Spring源码阅读(二)—— AOP
    业务开发(八)—— Maven
    高性能MySQL笔记
    Java源码阅读(六)—— ReentrantLock
    业务开发(六)—— MyBatis框架
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078857.html
Copyright © 2011-2022 走看看