[C ++] LeetCode: 66 Single Number

Source: Internet
Author: User

[C ++] LeetCode: 66 Single Number
Question:

Given an array of integers, every element appears twice should t for one. Find that single one.

Note:
Your algorithm shocould have a linear runtime complexity. cocould you implement it without using extra memory?

Ideas:

Requires linear completion without additional storage space.

** Very clever **

Use exclusive or to exclude double values. The rest is single one. Exclusive or interchangeable, and the order is variable.

For example, an array {2, 1, 4, 5, 2, 2, 1} is given. For example, returns an exception or, 2 ^ 1 ^ 4 ^ 5 ^ 2 ^ 4 ^ 1 <=> (2 ^ 2) ^ (1 ^ 1) ^ (4 ^ 4) ^ (5) <=> (0) ^ (0) ^ (0) ^ 5 = 5

AC Code:

 

Class Solution {public: int singleNumber (int A [], int n) {int ret; ret = A [0]; for (int I = 1; I <n; I ++) {ret ^ = A [I];} return ret ;}};


 

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.