• 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 }
    
    
    
     
  • 相关阅读:
    quartz 定时调度持久化数据库配置文件
    springboot项目下mvnw文件的作用
    mysql安装版卸载,解压版安装
    idea提示,格式化代码,清除不使用的包快捷键,maven自动导jar包
    JavaScript中call,apply,bind方法
    彻底理解js中this的指向
    Gradle系列之从init.gradle说起
    响应式网页设计简单入门
    开启MySQL远程访问权限 允许远程连接
    https原理
  • 原文地址:https://www.cnblogs.com/ncznx/p/9168201.html
Copyright © 2020-2023  润新知