Leetcode:single number III

Source: Internet
Author: User

Topic:

Given An array of numbers nums , in which exactly-elements appear only once and all the other elements appear exactly Twice. Find the 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. The above example, is [5, 3] also correct.
    2. Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity?

Analysis:

Two equal number XOR or result is 0. Therefore, for the first time, the array is scanned, resulting in two separate numbers a, B, or result axorb. Because A and B are unequal, Axorb must not be 0, and bits A and B bits 1 must be different. In any axorb, you can divide the elements of the original array into two sets of XOR results, which are not 0 bits.


Note: N & (-N) is n from low to high, the number corresponding to the first non-0 digit


Reference code:

Class Solution{public:    vector<int> singlenumber (vector<int>& nums)    {    size_t length = Nums.size ();        vector<int> results;    Results.reserve (2);    if (0 = = length) return results;        int axorb = 0;    for (size_t i = 0; i < length; i++)    Axorb ^= nums[i];        int mask = Axorb & (-axorb); Get Axorb from low to high, the first non-0 digits corresponding to the number    int a = 0;    int b = 0;    Axorb bits is 1 bits A and B must be different, using this non-1 bit to divide the original array elements into two sets of XOR results for    (size_t i = 0; i < length; i++)    {    if (Mask & N Ums[i]) a ^= nums[i];    else b ^= nums[i];    }    Results.push_back (a);    Results.push_back (b);    return results;}    ;


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode:single number III

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.