I'm also going to brush leetcode--1, single number.

Source: Internet
Author: User

The meaning of this topic is probably this:

Give me an array of integers with elements that appear two times, but one element appears only once, and you have to find the element that appears only once. It also requires that the time complexity of the algorithm be linear, i.e. O (N).

At first I thought for a long time, never found a way. If the element type is not defined as Integer, it is not possible to find the element that appears only once in linear time. So I think the breakout point should be that the element type is integer.

Why can an integer achieve a result within a linear time? I opened the label that the title belongs to, "bit manipulation"-bit operation. It seems like all of a sudden, bit manipulation is a magical thing, and it hides the philosophy of Boolean algebra behind it. Remember in the beginning to learn programming, exchange A, b two number can be used three times different or complete, then always think why.

So the breach of this topic has been found, the common bit operation has a "mask", and 1 for & operation, the result is unchanged, and 0 for the & operation, the position is 0. The bit operation to be used for this problem is "XOR", "XOR" has two features:

1, a number with any one of the different or two times, the result is the original number.

2, a number and 0 are different or, the result is the original number.

Ah! So it looks like the answer to this question is out!

1 classSolution {2  Public:3     intSinglenumber (vector<int>&nums) {4         intresult =0;5          for(Auto first = Nums.cbegin (); First! = Nums.cend (); first++) {6Result ^= *First ;7         }8         returnresult;9     }Ten};

I also want to brush leetcode--1, single number

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.