137. Single Number II

来源:互联网 发布:如何查看淘宝产品排名 编辑:程序博客网 时间:2024/06/13 10:37

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?



线性时间,常量空间

java中int是4字节,用一个32位的数组来存储每一位中1的个数,若循环一遍后,某位中1的个数不是3的倍数,则代表那个只出现一次的数的这位为1;

 public int singleNumber(int[] nums) {        int[] bit=new int[32];        for(int i=0;i<nums.length;i++){            for(int j=0;j<32;j++){                bit[j]+=(nums[i]>>j)&1;            }        }        int result=0;        for(int i=0;i<32;i++){            if(bit[i]%3!=0)                result|=1<<i;        }        return result;    }


0 0
原创粉丝点击