zoukankan      html  css  js  c++  java
  • Single Number II LeetCode Java

    描述
    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?

    分析
    本题和上一题 Single Number,考察的是位运算。
    方法 1:创建一个长度为 sizeof(int) 的数组 count[sizeof(int)],count[i] 表示所有元
    素的 1 在 i 位出现的次数。如果 count[i] 是 3 的整数倍,则忽略;否则就把该位取出来组成答案。
    方法 2:用 ones 记录到当前处理的元素为止,二进制 1 出现“1 次”(mod 3 之后的 1)的有哪
    些二进制位;用 twos 记录到当前计算的变量为止,二进制 1 出现“2 次”(mod 3 之后的 2)的有哪
    些二进制位。当 ones 和 twos 中的某一位同时为 1 时表示该二进制位上 1 出现了 3 次,此时需要
    清零。即用二进制模拟三进制运算。最终 ones 记录的是最终结果。

    给定整数数组,除一个元素外,每个元素出现三次,找到唯一的那个

    代码 

     1 class Solution {
     2   public static int singleNumber(int A[]) {
     3     if(A.length==0||A==null 4                  return 0 5    int cont=new int[32];
     6 
     7    for (int i = 0; i < A.length; i++) {
     8          for (int j = 0; j < 32; j++) {
     9                if(A[i}>>j&1)==1){
    10                     cont[j]++;
    11                } 
    12          }
    13 
    14    }
    15     int result = 0;
    16     for (int i = 0; i < 32; i++) {
    17        result += (cont[i] %3<< i);
    18     }
    19       return result;
    20   }
    21 }

     方法二

    
    
     1 // LeetCode, Single Number II
     2 // 方法 
     3 class Solution {
     4    public static int singleNumber(int A[], int n) {
     5        if(A.length==0||A==nullreturn A;
     6         n=A.length; 
     7         int ones = 0, twos = 0, threes = 0;
     8         for (int i = 0; i < n; ++i) {
     9            twos |= (ones & A[i]);
    10            ones ^= A[i];
    11            threes = ~(ones & twos);
    12            ones &= threes;
    13            twos &= threes;
    14         }
    15         return one;
    16    }
    17 }
    
    
    
     
  • 相关阅读:
    生成.project、.classpath文件
    Ecelipse上添加Server
    通信安全验证
    通过jstack定位在线运行java系统故障_案例1
    自动代码复制工具
    在Visual Studio Express 2013中开发自定义控件
    通过java类文件识别JDK编译版本
    去掉java反编译(JD-GUI)生成的源文件中注释
    循环处理目录下文件框架
    java查找重复类/jar包/普通文件
  • 原文地址:https://www.cnblogs.com/ncznx/p/9168201.html
Copyright © 2011-2022 走看看