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

【LeetCode】Single Number II

时间:2015-03-12 22:35:49      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:leetcode

     题意:

    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?


     思路:

     用 ones, twos, threes 分别记录数字在二进制表示中对应位置 1 出现的次数。变量更新如下:首先更新 twos, 对应位置出现两次的为上一次对应位置出现两次的加上一次出现一次的和新的数的与,ones 为对应位置出现一次的为上一次出现一次的异或上新的数,threes 为对应位置出现了一次的再与上出现了两次的位置。

     然后再把 ones 和 twos 中 含有 threes 中 1 的位置的那些去掉。

     这道题的位运算很微妙,值得好好体会。你可以想想 ones、twos 和 threes 是怎么来的?计算的先后顺序能不能变化?threes 为什么可以用 ones 和 twos 的值来算?


     代码:

     C++:

class Solution {
public:
    int singleNumber(int A[], int n) {
        int ones = 0, twos = 0, threes = 0;

        for(int i = 0;i < n;++i)
        {
            twos = twos | ones & A[i];
            ones = ones ^ A[i];
            threes = ones & twos;

            ones = ones & ~threes;
            twos = twos & ~threes;
        }

        return ones;
    }
};

    Python:

class Solution:
    # @param A, a list of integer
    # @return an integer
    def singleNumber(self, A):
        ones = 0
        twos = 0
        thress = 0
        
        for i in range(0,len(A)):
            twos = twos | ones & A[i]
            ones = ones ^ A[i]
            threes = ones & twos
            
            ones = ones & ~threes
            twos = twos & ~threes
            
        return ones

【LeetCode】Single Number II

标签:leetcode

原文地址:http://blog.csdn.net/jcjc918/article/details/43915525

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