zoukankan      html  css  js  c++  java
  • Single Number III

    Description:

    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:

    1. The order of the result is not important. So in the above example, [5, 3] is also correct.
    2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

    Code:

        vector<int> singleNumber(vector<int>& nums) {
            vector<int>result;
            if (nums.size() < 2)
                return result;
            int xorAll = 0;
            for (int i = 0; i < nums.size(); ++i)
                xorAll^=nums[i];
            unsigned int x = 1;
            while ((xorAll & x) == 0)
            {
                x=x<<1;
            }
            int result1=0,result2=0;
            for (int j = 0; j < nums.size(); ++j)
            {
                if ((nums[j]&x) == 0)
                    result1^=nums[j];
                else
                    result2^=nums[j];
            }
            result.push_back(result1);
            result.push_back(result2);
            return result;
        }

    PS:

    思路很清晰,但是写代码的是后老在细节出错,主要是两个判断条件要注意

  • 相关阅读:
    君の名は~ 观后感
    dp1,明天补题解
    【bzoj1222】[HNOI2001]产品加工
    Daily~Miracles
    luogu 1273有线电视网
    luogu 1373
    codeforces 721C
    codeforces 706E
    The~Best~Chanteur~宇多田ヒカル
    codeforces706D
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4752002.html
Copyright © 2011-2022 走看看