zoukankan      html  css  js  c++  java
  • leetcode-Single Number III 找独数

    Single Number III

    Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

    For example:

    Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

    Note:

    1. The order of the result is not important. So in the above example, [5, 3] is also correct.
    2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

    题意:

      有一个数组,除了两个单独存在的数其余都是成对存在的,找出这两个数。

      注: 尝试使用空间复杂度为常数的算法

    解题:

      如果有过类似题目的经验的话可以知道这道题目最好是使用比特运算得到结果的,当然使用哈希表在时间上也是非常快速的。

      但是如果我们使用比特运算,这里将会出现一个问题。以前我们碰到的找独数的题目,都是找一个数,而现在要找两个数。如果我们把所有的元素都进行异或运算后,得到的会是这两个数的异或结果,怎样才能把他们两个分开呢?

      这里使用了一个非常巧妙的方法,我们注意到由于这两个数是肯定不相等的,那么在异或运算之后结果的比特位肯定会有1的情况,这是表示这两个数在该比特位一个是0,一个是1。恰恰我们可以利用这一点,将两者分开!我们假设这个比特位是第k位。

      此时,我们可以再次遍历数组,将元素中第k比特位为0和1的分开成两队单独进行异或运算。这样一来,我们不仅保证了两队中都会有一个最后的独数,而且还确保了这两个队列中有且仅有这个数是单独的,其余元素仍然是成对出现。所以,这两组队列分别进行异或运算之后的结果就是我们想要的答案。解题成功。

    class Solution
    {
    public:
        vector<int> singleNumber(vector<int>& nums) 
        {
            // Pass 1 : 
            // Get the XOR of the two numbers we need to find
            int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());
            // Get its last set bit
            diff &= -diff;
    
            // Pass 2 :
            vector<int> rets = {0, 0}; // this vector stores the two numbers we will return
            for (int num : nums)
            {
                if (num & diff) // the bit is set
                {
                    rets[0] ^= num;
                }
                else // the bit is not set
                {
                    rets[1] ^= num;
                }
            }
            return rets;
        }
    };
    

       但可悲的是,我使用的是python语言,要想拿到某个数字的比特位是可以,使用bin()函数就行,但是该函数返回的字符串却是长度不一的!这让我在取某位比特位的时候经常碰到index out of range这样的错误。还是有点淡淡地伤感的,不过没关系,我们通过哈希表依然能快速的得到答案。

    >>> bin(1) #长度不一好痛苦。。
    '0b1'
    >>> bin(2)
    '0b10'
    >>> bin(9)
    '0b1001'
    
  • 相关阅读:
    Tp控制器
    thinkphp总体设计
    视频会议管理系统操作步骤(新)
    视频会议(旧)
    HCIE实验LAB_1(1)
    HCIE实验LAB_1(2)
    HCIE实验LAB_1(3)
    HCIE实验LAB_1(4)
    HCIE实验LAB_1(5)
    HCIE实验LAB_1(6)
  • 原文地址:https://www.cnblogs.com/Blaxon/p/4738371.html
Copyright © 2011-2022 走看看