Title Description: Given an integer array, find the main element, which in the array is strictly more than one-third of the number of elements in the array.
Example: Returning 1 to an array [1,2,1,2,1,3,3]
Before, there is a "main element" problem (see: Click to open the link), we use the "elimination method", because the number of main elements is greater than one-second of the total number of elements, you can save only one element of the hash table, the elimination method to solve.
Now that the condition has changed, it becomes greater than one-third. Then you can use a similar elimination method, so that the hash table stores two data, each data has its own count, each time the elimination of a small count of data (so that the count minus one), when the data is completely offset, the new data is replaced. In this way, we can only use a single traversal to get two numbers.
For example, take the following steps:
1. Initialize Sample1 = 1, count1 = 1; Sample2 = 2, Count2 = 1 (the first two elements), and then process the 3rd element 1
2. sample1 = 1, count1 = 2; sample2 = 2, Count2 = 1, handling 4th element 2
3. sample1 = 1, count1 = 2; sample2 = 2, Count2 = 2, handling 5th element 1
4. sample1 = 1, count1 = 3; sample2 = 2, Count2 = 2, handling 6th element 3
5. sample1 = 1, count1 = 3; sample2 = 2, Count2 = 1 (elimination of one), handling of 7th element 3
6. sample1 = 1, count1 = 3; sample2 = 2, Count2 = 0 (one more elimination), traversal completed
In this way, we get two elements 1 and 2, so who is the main element?
There is an idea that the value of the count is, in fact, not necessarily, if the main element and another element at some point the value of the count is equal, (we treat the equivalent of a random selection of a elimination) then the main element once removed, it is likely to remain in the "disadvantage", has been eliminated, although to the end can not be replaced But the count value will be smaller than the other one. Therefore, the more simple way is to save the two number of the array to do a traversal to see who is more, the main element is who. (I don't know if there's any better way to go through the results at once).
The code is as follows:
Class solution: "" "@param nums:a List of integers @return: The majority number occurs more than 1/3" "" D EF Majoritynumber (Self, nums): sample1, Sample2 = Nums[0], nums[1] count1, count2 = 0, 0 cur, n = 0, Len (nums) while cur! = n:if nums[cur] = = sample1:count1 + 1 elif nums[cur] = = Sample2:count2 + 1 else:if count1 >= count2:count1- = 1 Else:count2-= 1 if count1 < 0:sample1 = Nums [cur] if count2 < 0:sample2 = Nums[cur] cur + = 1 cur = 0 Co Unt1, Count2 = 0, 0 while cur! = n:if nums[cur] = = sample1:count1 + 1 Elif Nums[cur] = = Sample2:count2 + 1 cur + 1 return sample1 if count1 > Count2 E LSE Sample2 # WRITe your code here
Main element II