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

  • 相关阅读:
    hdu 1199 Color the Ball 离散线段树
    poj 2623 Sequence Median 堆的灵活运用
    hdu 2251 Dungeon Master bfs
    HDU 1166 敌兵布阵 线段树
    UVALive 4426 Blast the Enemy! 计算几何求重心
    UVALive 4425 Another Brick in the Wall 暴力
    UVALive 4423 String LD 暴力
    UVALive 4872 Underground Cables 最小生成树
    UVALive 4870 Roller Coaster 01背包
    UVALive 4869 Profits DP
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214736.html
Copyright © 2011-2022 走看看