[LeetCode] Single Number II

来源:互联网 发布:php 在线拍卖系统源码 编辑:程序博客网 时间:2024/05/01 16: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?

分析:

这道题的难点在于,需要用constant space来解决。如果没有这个要求的话,自然是好说。思路是:每一个int都是4个byte,也就是32个bit。那么我们可以来数bit。那些出现三次的数对应的为1的bit和一定可以被三整除;而那个只出现了一次的数对应的为1的bit的和肯定不能被3整除。所以我们只需要保存一个32位的counter,来累计各个为1的bit的个数。


代码:

class Solution {public:    int singleNumber(int A[], int n) {        int count[32] = {0};int result = 0;for (int i = 0; i < 32; i ++) {for (int j = 0; j < n; j ++) {int num = A[j];count[i] += (num >> i) & 1;}result |= ((count[i] % 3) << i);}return result;    }};



0 0
原创粉丝点击