LeetCode:Single Number II

题目:

    Given an array of integers, every element appearsthree 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?


解题思路:

    思路类似基数排序,将所有数字列成n行,然后观察其中的一列,你会发现,由于其他数字都出现了


三次,如果当前这列某个数位的个数不能被3整除,那么,所要求的数在此位必等于这个数位的值,这样


就能以O(n)的时间复杂度解决问题了(注:此处常系数是10).


下面是解题代码.

class Solution {
public:
    int singleNumber(int A[], int n) 
    {
        int div[10] = {1} , cnt = 0 , res = 0;
        for(int i=1;i<10;++i)
            div[i] = div[i-1] * 10 ;
        for(int i=0;i<n;++i)
            cnt +=A[i] < 0 ;
        for(int i=1;i<=10;++i)
        {
            int hash[10] = { 0 } ;
            for(int j=0;j<n;++j)
                ++hash[abs((long long)A[j])/div[i-1]%10];
            for(int j=0;j<10;++j)
                if(hash[j] % 3)
                    res = j * div[i-1] + res ;
        }
        return cnt % 3 ? -res : res ;
    }
};

注:abs((long long)A[j])中要将A[j]强制转换为long long型,不然程序有bug,比如A[j]等于-2^31.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值