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测试程序源码

  • 相关阅读:
    pip安装requests时报 Requirement already satisfied: requests in d:pythonpyth... 的问题解决
    渗透测试靶场
    Spring Security核心类关系图
    Spring security 5 Authorize Configuration
    固定技术栈
    redis 指定端口 启动
    Spring 获取当前activeProfile
    通过进程编号 查询 监听端口
    lombok 插件安装
    idea 快捷键设置
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214736.html
Copyright © 2011-2022 走看看