Single number III

Source: Internet
Author: User
Tags diff

Given An array of numbers nums, in which exactly, elements appear only once and all the other elements appear exactly t Wice. Find the elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:
The order of the result is not important. The above example, [5, 3] is also correct.

Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity problem solving skills:
This problem is similar to the single number, Numberii, and we can find a way to divide the two only occurrences into two different groups, and then call the method in the individual numbers to get the result. The practice is: first we can all the number of XOR, this will get two different number of differences or results, and then, X &=-X to remove the right end of the number a bit of 1, and then the number of the original array and operation, the two different numbers are divided into different groups, Finally, we can get the final result by making the difference or operation of the numbers in two groups.
Code:

#include <iostream>
#include <vector>
using namespace std;

int XOR (vector<int>& nums)
{
	int sum = 0, Len = nums.size ();
	for (int i = 0; i < len; i++)
	{
		sum = sum ^ nums[i];
	}
	return sum;
}

Vector<int> Singlenumber (vector<int>& nums) {
	int diff;
	diff = XOR (nums);
	Diff &=-diff;
	vector<int> Res (2, 0);
	for (int i = 0; i < nums.size (); i++)
	{
		if (diff & Nums[i]) res[0] = Res[0] ^ nums[i];
		else res[1] = res[1] ^ nums[i];
	}
	return res;
}

int main ()
{
	vector<int> nums, res;
	int x;
	while (CIN >> x)
		nums.push_back (x);
	res = Singlenumber (nums);
	for (int i = 0; i < res.size (); i++)
		cout << res[i] << Endl;
	System ("pause");
}


Related Article

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.