The sword refers to the offer--. Question 40: A number that appears only once in an array

Source: Internet
Author: User

Title: In an array of shapes except for two digits, the other numbers appear two times. Please write the program to find the two only occurrences of the number. The time complexity is O (n) and the space complexity is O (1).

Idea: The topic is very strict, O (n) time complexity, O (1) space complexity. The difficulty is not small. Refer to the book on the idea, the realization of the time, is mainly to make up for the lack of experience in bit computing.

Here is my code, implemented in C + +:

void findnumappareonce (const int data[], const int length, int * num1, int * num2) {if (data = NULL | | length < 2) retur  N;int ident = 0;for (int i = 0; i < length; ++i) ident ^= data[i];const int bitposi = GETFIRSTBITIS1 (ident); *num1 = *num2 = 0;for (i = 0; i < length; ++i) {if (IsThisBit1 (Data[i], Bitposi)) *num1 ^= data[i];else*num2 ^= data[i];}}

The two functions involved in bit operations are as follows:

const int GETFIRSTBITIS1 (int ident) {int num = 0;while (((Ident >> num) & 0x1) = = 0) && (Num < (sizeof (int) * 8))//take care of the bit operators! (Of course with parentheses) + + Num;return num;} const BOOL ISTHISBIT1 (int data, const int POS) {return Data & (0x1 << POS);//there is a warning here.}

Test section:

#include <iostream.h>const int L = 10; int main () {const int Test[l] = {2, 3, 3, 2, 5, 5,, 8, 8};int A, B; Findnumappareonce (test, L, &a, &b) cout << a << "" << b << endl;return 0;}

The problem is very special and is hereby recorded. Temporarily do not promote, do not think more complex situation.

The sword refers to the offer--. Question 40: A number that appears only once in an array

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.