Sword refers to an offer---a character that appears only once in an array

Source: Internet
Author: User
topic:

In an integer array, except for two digits, the other numbers appear two times, please write out the program to find the two occurrences of only one number, requiring time complexity O (n), space complexity of O (1). parsing:


void FindNum (int* arr, int length)
{
	if (arr = = NULL | | | length < 2)
	{return
		;
	}
	int tty = arr[0];
	for (int i = 1; i < length; ++i)
	{
		tty = Tty^arr[i];
	}
	At this time out of the loop, TTY for two occurrences of only one number of the difference or value
	//Now need to determine the minimum bit of TTY 1 at which bit
	int index = 0;
	int num1 = 0;
	int num2 = 0;
	for (int j = 0; J < 32;++j)
	{
		if (tty& (1 << index)) = = (1 << index))
		{
			break;
  
   }
		Else
		{
			++index;
		}
	}
	At this point, you need to divide the two occurrences only once into two groups for
	(int p = 0; p < length; ++p)
	{
		if (arr[p]& (1 << index) = = (1 <& Lt Index))
		{
			num1 = num1^arr[p];
		}
		else
		{
			num2 = num2^arr[p];
		}
	}
	cout << num1 << Endl;
	cout << num2 << Endl;
}
  

void Test ()
{
	int arr[] = {1, 2, 3, 4, 5, 3, 2, 1};
	int length = sizeof (arr)/sizeof (arr[0));
	FindNum (arr, length);
}

int main ()
{
	Test ();
	System ("pause");
	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.