• 【leetcode】Single Number II (medium) ★ 自己没做出来....


    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的次数!!!  可以对每一位统计,也可以对期望出现的次数统计。

    答案来自:http://blog.csdn.net/jiadebin890724/article/details/23306837

    解法一:
            int 数据共有32位,可以用32变量存储 这 N 个元素中各个二进制位上  1  出现的次数,最后 在进行 模三 操作,如果为1,那说明这一位是要找元素二进制表示中为 1 的那一位。代码如下:
    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int bitnum[32]={0};
            int res=0;
            for(int i=0; i<32; i++){
                for(int j=0; j<n; j++){
                    bitnum[i]+=(A[j]>>i)&1;
                }
                res|=(bitnum[i]%3)<<i;
            }
            return res;
        }
    };
    时间:O(32*N),这是一个通用的解法,如果把出现3次改为 k 次,那么只需模k就行了。
     
    解法二:
            这是一个更快一些的解法,利用三个变量分别保存各个二进制位上 1 出现一次、两次、三次的分布情况,最后只需返回变量一就行了。代码如下:
     
    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;
        }
    };
           解释:每次循环先计算 twos,即出现两次的 1 的分布,然后计算出现一次的 1 的分布,接着 二者进行与操作得到出现三次的 1 的分布情况,然后对 threes 取反,再与 ones、twos进行与操作,这样的目的是将出现了三次的位置清零。
            这个方法虽然更快、更省空间了,但是并不通用。
     
     
    我觉得不出现3次的那个数字可能不止出现了一次,所以加了一个取余的判断。
    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;
            }
            if(n%3 == 1)
            {
                return one;
            }
            else if(n%3 == 2)
            {
                return two;
            }
        }
    };
  • 相关阅读:
    巴塞尔协议
    商业银行资本充足率
    开源录屏软件Open Broadcaster Software
    简介二:操作系统和集群开源技术研究
    【Python】 零碎知识积累 II
    【Python】 用户图形界面GUI wxpython IV 菜单&对话框
    【Python】 关于import和package结构
    【Python】 魔法方法
    【Python】 闭包&装饰器
    【Python】 迭代器&生成器
  • 原文地址:https://www.cnblogs.com/dplearning/p/4110804.html
Copyright © 2020-2023  润新知