Find out which of the 2n + 1 numbers is not paired

Source: Internet
Author: User

Problem definition:There is a 2n + 1 number, with only one single vertex. Everything else is in pairs. Find the single vertex number. For example, 2 1 3 2 1. 3 is the answer.

Thought 1:Brute force search-compare each number with other numbers. If the same number is not found, the result is displayed. The time complexity is O (n2)

Thought 2:Sort search-first sort the sequence, and then find a pair from the front to the back until it is not paired. Time complexity, how can I get o (nlgn)

Thought 3:An exception or computing task. Time complexity O (N)

Let's look at Idea 3:
Principle:XOR operation (^) -- (BitFor example, 1 ^ 0 = 1, 1 ^ 1 = 0

In this way:

  • The two identical numbers are equal to or equal to 0.
  • Any number is different from zero or oneself (converted in place. 1 ^ 0 = 1, 0 ^ 0 = 0)

For example:5 ^ 5 = 0

5 ^ 0 = 5

 

For this question: 2 1 3 2 1, all are different or a bit: the same (2 ^ 2, 1 ^ 1) is 0, and the remaining 3 and 0 are different or their own 3.(Note:Exclusive or exclusiveExchange Law)

Reference code:

#include <stdio.h>int main(){      int a[5] = {2, 1, 3, 2, 1};      int aim = a[0];      for(i = 1; i < 5; i++)       {            aim = aim ^ a[i];        }        printf("Result:", aim);        return 0;}

The difference or is quite good in this regard. Another application:

There is no need for a third number to directly exchange two numbers:

#include <stdio.h>void swap(int *a, int *b){    *a = *a ^ *b;    *b = *a ^ *b;    *a = *a ^ *b;}int main(){    int a=3, b=5;    swap(&a, &b);    printf("%d\n%d", a, b);    return 0;}

Of course, the same thinking can be used to complete this question:

#include <stdio.h>void swap(int *a, int *b){    *a = *a + *b;    *b = *a - *b;    *a = *a - *b;}int main(){    int a=3, b=5;    swap(&a, &b);    printf("%d\n%d", a, b);    return 0;}

 

 

 

 

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.