首页 > 其他 > 详细

[leetcode] Single Number II

时间:2014-12-01 12:48:12      阅读:276      评论: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?

思路:

这道题目开始没做出来,没有任何进行位运算的思想。这里亟需提高。

看了别人写的,才豁然开朗。统计所有数字每一位是1之和,并按3取模。因为数字或者出现1次,或者出现3次,所以这个结果或者为0,或者为1。如果不是0,就说明那个出现一次的数字在这一位为1。

举个例子,(4,7,7,7),对应二进制(100,111,111,111)。最低位,(1+1+1+0)%3=0,最高位(1+1+1+1)%3=1,这说明出现一次的数字(4)最高位为1。

题解:

class Solution 
{
public:
    int singleNumber(int A[], int n) 
    {
        int result = 0;
        int sum = 0;
        int base = 0;
        for(int i=0;i<32;i++)    //int是32位
        {
            base = 1<<i;
            sum = 0;
            for(int j=0;j<n;j++)
                if(A[j]&base)
                    sum = (sum+1)%3;

            if(sum)
                result |= base;
        }
        return result;
    }
};

 

后话:

这种方法感觉通用性差,只是针对题目给定的情况,如果数组中还包括出现两次的数字,这种方法就失效了。

后来又找到了一种更好的方法,到现在还没有完全的理解这种思想,先放着,以后再说吧

解法二:

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];  
            //cout<<one<<endl;  
            three=one&two;  
            one&= ~three;  
            two&= ~three;  
        }  
        return one;  
    }  
};  

 

[leetcode] Single Number II

原文:http://www.cnblogs.com/jiasaidongqi/p/4134648.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!