Leetcode Single number I & II Meet the additional requirements of two problems in general solution and thinking process

Source: Internet
Author: User
Tags bitwise
Single Number

Given an array of integers, every element appears twice for one. Find is single one.

Note:
Your algorithm should have a linear runtime. Could you implement it without using extra memory?

Single II

Given an array of integers, every element appears three times except for one. Find is single one.

Note:
Your algorithm should have a linear runtime. Could you implement it without using extra memory? first instinct to think of an algorithm, but the brain a turn, think is to O (n*n) time complexity. Compiled, and sure enough, did not pass. The procedure is as follows: But I think this algorithm is the simplest, and versatility is the best.

int singlenumber (int a[], int n) {for
		(int i = 0; i < n; i++)
		{
			if (count (a, a + N, A[i]) <2) return
				I ;
		}
	}

Then racking think that the algorithm can be optimized for the complexity of Time O (n). Divide and conquer. Reduced treatment. Greedy. Dynamic planning ... Think much. Well, instinctively analyze it:

1. Request complexity O (n), the vernacular point is that can not be in an n-cycle inside the Add any loop, the previous failure is because of this reason. But you can add loops outside the loop ...

2. Now that you can add loops outside of the lookup loop, what kind of loop do you want to add? Sort it, yes. The sort of sequence is easy to do. (Feeling this conclusion also applies to many places)

After sorting, it is easy to calculate how many times a number appears in the series. How many times in a row is the total number of times, it is convenient. O (∩_∩) o~ then began to write code, wait. I think we should consider the special situation before I start. Special cases are generally border issues:

1. If it is a series of outer space.

2 If the first is single number.

3 If the last one is single number. Well, you can write the code after the analysis. The following code is suitable for two problems, just change the number of occurrences to the corresponding 2 or 3 times. And there's no need for extra space.

Good versatility, suitable for two situations
	int singlenumber (int a[], int n) {
		//special Case 1,2
		if (n<=0) return-1;
		if (n==1) return a[0];

		Sort (A, a + N);
		int j = 1;
		for (int i = 0; i < n-1 i++)
		{
			if (a[i] = = a[i+1])
				j + +;
			else 
			{
				if (j<2) return a[i];//is modified here to j<3 so that it can be applied to single number II.
 				j = 1;
			}
		}

		Special Case 3 The last one is special case of single number return
		a[n-1];
	}

relatively simple.

2014-3-6 Update:
Well, the update doesn't say versatility anymore. The above basic sorting processing is indeed very common, is the basic algorithm content, there is nothing worth in-depth discussion.
I can't believe this article is lucky to have so many people to read. Here to update the commentary. There are three kinds of solutions to the subject type: 1 as the above sort of processing Method 2 using map processing, efficiency is also close to O (n) 3-bit Operation solution-here also can be divided into two kinds of solutions
The following procedure is the use of unordered_map to solve single number I program (single number II is the same reason):

2014-2-18 Update
	int singlenumber (int a[], int n) 
	{
		unordered_map<int, bool> Ump_ii;
		for (int i = 0; i < n; i++)
		{
			if (!ump_ii.count (A[i])) ump_ii[a[i] = true;
			else Ump_ii.erase (A[i]);
		}
		Return Ump_ii.begin ()->first;
	}


Here is a single number I of the bitwise operation solution, the idea is that each bit appears 2 times to clear zero, so you can continue to vary or calculate the final result:

2014-2-18_2 Update
	int singlenumber (int a[], int n) 
	{
		int ans = 0;
		for (int i = 0; i < n; i++) ans ^= a[i];
		return ans;
	}



Two solutions to the bitwise operation of single number II--Reference to Leetcode forum code:

Method One, the 32 bit of int is handled individually-this method is fairly simple:

int singlenumberii_36 (int a[], int n)
{
	int ans = 0;
	for (int i = 0; i < i++) 
	{
		int c = 0, d = 1<<i;
		for (int j = 0; J < N; j +)
			if (A[j] & D) c + +;

		if (c%3) ans |= D;
	}
	return ans;
}


Method Two, carry, mask clear 0 Method-This method is still very difficult to understand, to be very careful, otherwise, it is easy to make mistakes, the bit is not familiar with the operation is difficult to write out.

int singlenumber (int a[], int n)
{
	int one = 0, two = 0;
	for (int i = 0; i < n; i++)
	{
		two |= a[i] & one;//two accumulate value one
		^= A[i];//one keep seeking anti
		int t = one &am P two;//the third time, one and two both retained the bit value one
		&= ~t;//0 three times the value of that bit two &= ~t
		;
	}
	return one;
}

Well, there are other single number II mutation bit algorithms, but it's not very well understood. Single numberii can be said to be as high as 5 stars difficult.

However, the above bit arithmetic is a good understanding of the, but also relatively easy to use in other situations, such as all numbers have appeared 5 times one of them, I think the interview should be the first algorithm.


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.