Single Number II

来源:互联网 发布:织梦cms如何仿站 编辑:程序博客网 时间:2024/06/06 21:45

Given an array of integers, every element appears three times except for one. Find that single one.

这一题好难啊。一点头绪都没有,要求是线性时间复杂度,同时要求常数项空间。

答案上,是这样来的。使用了位运算。ps:感觉用到位运算的题目都好难。

如果对所有数字的第i位bit进行统计的话,会发现对3取余之后只会出现0或者1.因为每个数要不出现三次要不就只出现1次。

通过这个规律可以得到以下代码:

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




0 0
原创粉丝点击