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?

    思路是用一个32位的数result的每一位记录所有数在这一位出现的次数,如果是3的倍数则消去,最后留下来的数则是所要的结果。

    注意,result需要定义为unsigned int类型,否则会出现负数的情况。

     1     int singleNumber(int A[], int n) {
     2         // Note: The Solution object is instantiated only once and is reused by each test case.
     3         unsigned int result = 0, MASK;
     4         int i, j, tmp;
     5         for(i = 0; i < 32; i++){
     6             MASK = 1<<i;
     7             tmp = 0;
     8             for(j = 0; j < n; j++){
     9                 tmp += ((A[j]&MASK) > 0 ? 1:0);
    10             }
    11             result |= ((tmp%3)>0 ? MASK:0);
    12         }
    13         return result;
    14     }
  • 相关阅读:
    网络流24题题解
    NOIP2018游记
    AGC016题解
    雅礼集训总结
    数学相关【真·NOIP】
    NOIP2018系列
    洛咕P4180 严格次小生成树
    矩阵乘法学习笔记
    一些比较神奇的思路
    点分治复习记
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3361831.html
Copyright © 2011-2022 走看看