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 }
 
  

 

 

 

转载于:https://www.cnblogs.com/ncznx/p/9168201.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值