Single Number II

来源:互联网 发布:手机淘宝扫一扫 编辑:程序博客网 时间:2024/04/30 06:42

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?

思路:int是4个byte存储,32bit, 数组中只有一个数字出现一次之外,其他数字都出现了3次,这个可以扩展到出现n次。
把所有的数字都写成二进制的形式,每一位要么是0要么是1,3个相同的数字的对应每一位都是相同的,从1-32位中,对于第i位,求出所有数字在第i位出现1的总共的次数count1

  1. single number的第i位为0,那么count1肯定是3的倍数
    2.single number的第i位为1,那么count1肯定不是3的倍数

    根据每一位count1就可以知道single number的每一位是多少,根据或运算就可以得到最终的结果。

public class Solution {      public  int singleNumber(int[] nums) {        if(nums.length==0) return -1;        int length=nums.length;         int temp=1;        int res=0;        for(int i=0;i<32;i++,temp=temp<<1)        {            int count1=0;            for(int j=0;j<length;j++)            {   if(((nums[j]) & temp)!=0)                  count1++;            }            if(count1%3!=0)                 res=res|temp;        }        return res;    }}
0 0