码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Single Number II 单独的数字之二

时间:2015-01-31 14:21:18      阅读:324      评论:0      收藏:0      [点我收藏+]

标签:

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?

 

这道题是之前那道单独的数字的延伸,那道题的解法就比较独特,是利用计算机按位储存数字的特性来做的,这道题就是除了一个单独的数字之外,数组中其他的数字都出现了三次,那么还是要利用位操作来解此题。我们可以建立一个32位的数字,来统计每一位上1出现的个数,我们知道如果某一位上为1的话,那么如果该整数出现了三次,对3去余为0,我们把每个数的对应位都加起来对3取余,最终剩下来的那个数就是单独的数字。代码如下:

 

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

 

还有一种解法,思路很相似,用3个整数来表示INT的各位的出现次数情况,one表示出现了1次,two表示出现了2次。当出现3次的时候该位清零。最后答案就是one的值。

  1. ones   代表第ith 位只出现一次的掩码变量
  2. twos  代表第ith 位只出现两次次的掩码变量
  3. threes  代表第ith 位只出现三次的掩码变量

 

class Solution {
public:
    int singleNumber(int A[], int n) {
        int one = 0, two = 0, three = 0;
        for (int i = 0; i < n; ++i) {
            two |= one & A[i];
            one ^= A[i];
            three = one & two;
            one &= ~three;
            two &= ~three;
        }
        return one;
    }
};

 

[LeetCode] Single Number II 单独的数字之二

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4263927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!