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的数组a,a[i]表示所有数字在i位出现的次数。
    假如a[i]是3的整数倍,则忽略;否则就把该位取出来组成答案。
    空间复杂度O(1).

    int sol1(int A[], int n)
    {
        int count[32];
        int result = 0;
        for (int i = 0;i < 32;++i) {
            count[i] = 0;
            for (int j = 0;j < n;++j) {
                if ((A[j] >> i) & 1) count[i] = (count[i] + 1) % 3;
            }
            result |= (count[i] << i);
        }
        return result;
    }

    另一个方法,同样的原理,用3个整数来表示INT的各位的出现次数情况,one表示出现
    了1次,two表示出现了2次。当出现3次的时候该位清零。最后答案就是one的值。

    int sol2(int A[], int n)
    {
        int one = 0, two = 0, three = 0;
        for (int i = 0;i < n;++i) {
            two |= one & A[i];
            one ^= A[i];
            three = one & two;
            one &= ~three;
            two &= ~three;
        }
        return one;
    }

     1 public class Solution {
     2     public int singleNumber(int[] A) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         int count[] = new int[32];
     5         int result = 0;
     6         for (int i = 0; i < 32; i ++){
     7             for (int j = 0; j < A.length; j ++) {
     8                 if (((A[j] >> i) & 1) == 1) 
     9                     count[i] = (count[i] + 1) % 3;
    10             }
    11             result |= (count[i] << i);
    12         }
    13         return result;
    14     }
    15 }
  • 相关阅读:
    Linux(Centos)安装图形化界面步骤
    Delphi 取得桌面文件夹的路径和取得我的文档的路径
    Nginx [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
    待查消息
    WM_SETFOCUS和WM_KILLFOCUS、WM_GETDLGCODE、CM_ENTER...
    WM_SIZE
    MongoDB 开启与关闭
    log4j 日志文件路径
    wamp中修改配置支持多站点
    java 下载示例
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3362972.html
Copyright © 2011-2022 走看看