首页 > 代码库 > [LeetCode] Single Number II

[LeetCode] Single Number II

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?

 

Answer: 这个算法的思路,就是数每一位上1的个数综合。既然有假设共有3n+1个数字,如果单例数字中的这一位为1,那么最终这一位的1的个数肯定为3k+1,k为某一整数。

 

最直白的思路是直接对数组进行遍历,然后对没一个元素进行位操作,最后让每个个数对3求余。其实没有那么麻烦。既然是对3求余,那么我们可以直接用3个数做位标记,看该位上1出现了0次1次2次还是3次?如果出现了3次,那么直接清零即可。

下面直接插入代码:

public class Solution {    public int singleNumber(int[] A) {        int one = 0; // the first time        int two = 0; // the second time        int three = 0; // the third time                for (int i=0; i<A.length; i++) {            three = two & A[i];            two = two | A[i] & one;            one = one | A[i];                        one = one & ~three;            two = two & ~three;        }                return one;    }}

 

[LeetCode] Single Number II