LeetCode(260) 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:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

分析

给定一个无序数组,内含两个只出现一次的元素,其余元素均出现两次,找出这两个元素。

要求,线性时间,常量空间。

AC源码

class Solution {
public:
    //方法一:借助数据结构unordered_set,占用了额外O(n)的空间
    vector<int> singleNumber1(vector<int>& nums) {
        if (nums.empty())
            return vector<int>();

        int len = nums.size();

        unordered_set<int> us;
        for (int i = 0; i < len; ++i)
        {
            if (us.count(nums[i]) == 0)
                us.insert(nums[i]);
            else
                us.erase(nums[i]);
        }//for

        return vector<int>(us.begin(), us.end());
    }

    //方法二:线性时间复杂度,常量空间复杂度
    vector<int> singleNumber(vector<int>& nums) {
        if (nums.empty())
            return vector<int>();

        int len = nums.size();
        int res = 0;
        for (int i = 0; i < len; ++i)
        {
            res ^= nums[i];
        }//for

        vector<int> ret(2, 0);
        //利用位运算,将原数组一分为二,每个部分含有一个只出现一次的数字,其余数字出现两次
        int n = res & (~(res - 1));
        for (int i = 0; i < len; ++i)
        {
            if ((n & nums[i]) != 0)
            {
                ret[0] ^= nums[i];
            }
            else{
                ret[1] ^= nums[i];
            }//else
        }//for

        return ret;
    }
};

GitHub测试程序源码

原文地址:https://www.cnblogs.com/shine-yr/p/5214736.html