zoukankan      html  css  js  c++  java
  • 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测试程序源码

  • 相关阅读:
    VS2008环境下CEGUI 0.7.1及相关工具的编译(转载 + 额外的注意事项)
    Makefile的学习
    Erlang 程序文档(转)
    erlang 二进制数据
    erlang中命令行传参,以及类型等。
    笔记:JAVA的静态变量、静态方法、静态类
    关于手机定位方案设计
    转:eclipse技巧
    DXUT CD3DArcBall类
    关于模型转向自然化思考
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214736.html
Copyright © 2011-2022 走看看