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 }
    
    
    
     
  • 相关阅读:
    解析ASP.NET Mvc开发之删除修改数据
    JavaScript module pattern精髓
    Remote验证及其改进(附源码)
    图模型的精确推理
    C#在泛型类中,通过表达式树构造lambda表达式
    类管理指针成员
    朴素贝页斯分类法
    使用Repository模式构建数据库访问层
    利用MVC的过滤器实现url的参数加密和解密
    在多线程中使用静态方法是否有线程安全问题
  • 原文地址:https://www.cnblogs.com/ncznx/p/9168201.html
Copyright © 2011-2022 走看看