Single Number Problems

Source: Internet
Author: User

The leetcode has the following two single number problems:

1. Assume that all elements in an integer array appearTwoOnly one element appears once. Find the element that appears once.

2. Assume that all the elements in an integer array appear3.Only one element appears once. Find the element that appears once.

Obviously, the only difference between the two problems is whether most elements appear twice or three times.


For problem 1: it is a good solution. Through the exclusive or operation, we can eliminate all elements that appear twice a ^ A = 0; in the end, only the element that appears once is 0 ^ B = B.

int singleNumber(int A[], int n){    int result=0;    for(int i=0; i<n; i++)    {        result ^= A[i];    }    return result;}

For Question 2: it is clear that we cannot continue to solve the problem by using an exclusive or bitwise operation. From the binary perspective, a number is nothing more than 0 and 1. If we only look at each bit, we add the content of this bit to the modulo 3, the resulting number is the value on this bit. With the value of a single number in each bit, the remaining number is displayed. In this case, we need an array of 32 to save this number. This space does not change with the increase of the N value of the array, so there is no problem from the perspective of space.

int singleNumber(int A[], int n){    int a[32] = {0};    int result=0;    for(int i=0; i<32; i++)    {        for(int j=0; j<n; j++)        {            if((A[j]>>i)&0x1 == 1) a[i]++;        }        result |= ((a[i]%3)<<i);    }    return result;}

Of course, there is another easier solution to this problem after you click the open link.





Single Number Problems

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.