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

  • 相关阅读:
    入门OJ 1278【关系网络】
    HDU 1372【Knight Moves】
    ZOJ 1047【Image Perimeters】
    log4J——在Spring中的使用
    实用性很强的文章(不来源于博客园)
    详解AOP——用配置文件的方式实现AOP
    Spring与Web项目整合的原理
    IOC——Spring的bean的管理(注解方式)
    IOC——Spring的bean的管理(xml配置文件)
    关于XML文件
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214736.html
Copyright © 2011-2022 走看看