LeetCode-Single Number II

Posted petewell

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-Single Number II相关的知识,希望对你有一定的参考价值。

LeetCode地址:https://leetcode.com/problems/single-number-ii/

Problem:
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?

思路

  • 将数组A中每个整形的二进制 分散到一个32位数组A上求和,出现3次的在该位上的和肯定是3的倍数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class  
public int singleNumber(int[] A)
int ret=0,index=0;
int[] binarySum=new int[32];
if(A==null || A.length==0)
return ret;

for(int i=0;i<A.length;i++)

index=0;
do

binarySum[index++]+=A[i]%2;
A[i]/=2;
while(A[i]!=0);



for(int i=0;i<binarySum.length;i++)

index=binarySum[i]%3;
if(Math.abs(index)>1)

index=(index+3)%3;

ret+=Math.pow(2, i)*(index);


return ret;


原文:大专栏  LeetCode-Single Number II


以上是关于LeetCode-Single Number II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-Single Number II-137

leetcode-Single Number III-260

Single Number II

137. Single Number II

137. Single Number II

LeetcodeUgly Number II