"Leetcode"--260. Single number III

Source: Internet
Author: User

Problem Description:

https://leetcode.com/problems/single-number-iii/

In an array, only two elements appear only 1 times, and the rest appear two times. Find out only those two that appear once (A, b).

Constant space, linear time is required.

Problem solving:

This problem uses "magical bit arithmetic".

1. Because in addition to the special two elements, the remaining 22 appears, then the idea of XOR (XOR).

2. After XOR from beginning to end, a XOR B result is obtained. Next we try to separate the two elements.

3. We find any one xor[diff_pos] = 1 in a XOR B, then we know that A and B are not the same on Diff_pos. If you follow Diff_pos, this value

Categories can divide all the numbers into two groups: 1) diff_pos = 0 elements, 2) Diff_pos = 1 elements.

4. For the two groups in the 3 group XOR, because the remaining elements are 22 appear, then finally left A/b.

The code is as follows:

classsolution (object):defSinglenumber (Self, nums): Xor=0 forNuminchNums:xor= xor^Num Diff_pos=0 forIinchRange (31):            if(Xor & (1 <<i)): Diff_pos=I BreakRec=[0,0] forNuminchNums:if(Num & (1 <<diff_pos)): rec[1] ^=NumElse: rec[0]^=NumreturnRec

The paper has not yet looked, again in the blind engage ...

"Leetcode"--260. 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.