Algorithm---more than half occurrences

Source: Internet
Author: User
Tags array length hash sort time 0
numbers that occur more than half of the Times Title Description

Title: There is a number in the array that appears more than half the length of the array to find this number. Analysis and Solution

There are many numbers in an array, and now we're going to find out which one of them is more than half the total number. When we come across something that is messy and disorderly, our people's inner-nature expectations are to sort it into order. So, we score two situations to discuss, unordered and orderly. Solution One

If it is unordered, then we can first sort all the numbers in the array (as for the sorting method to pick the most common quick sort). After the sequence, the direct traversal, in the whole array of traversing the same time to count the number of occurrences of each digit, and then the number of occurrences more than half of the direct output, the problem is completed. The total time complexity is O (Nlogn + N).

But what if it's an ordered array, or is it sorted to turn an unordered array into an ordered array? It is also necessary to traverse the entire array once the sequence O (NLOGN) is completed.

We know that since it is an array, we can direct to a certain number based on the array index support. We find that a number is more than half the number of occurrences in an array, so it must be the number at the N/2 of the ordered array index (zero-based). Since then, we only need to complete the entire array after the order, and then directly output the array of N/2 in the number, which is the whole array of occurrences more than half of the number, the total time complexity due to the lack of the last iteration of the entire array, reduced to O (N*logn).

However, there is no intrinsic change in time complexity and we need to find a more effective way of thinking. Solution Two

It is necessary to reduce the total time complexity, then you can use the search time complexity of O (1) hash table, that is, space to change time. The hash table's key value (key) is the number in the array, and the value is the number that corresponds to the number. Then go straight through the entire hash table, find out the number of each digit in the corresponding position of the number of times, output that the number of occurrences more than half of the numbers can be. Solution Three

Hash table requires O (n) space overhead, and to design a hash function, there is no better way. We can try to think about it, if we delete two different numbers at a time (whether we're looking for more than half the number of occurrences), the number we're looking for in the rest of the number (more than half of the occurrences) still exceeds half the total number of occurrences. By repeating the process repeatedly, the other numbers are eliminated, and the number that appears more than half is finally found. This method eliminates the ordering, and avoids the overhead of the space O (n), in the sense that the time complexity is only O (n) and the space complexity is O (1), which seems to be the best method.

For a simple example, such as array a[5] = {0, 1, 2, 1, 1};

Obviously, if we want to find out more than half the number of occurrences in array A, this number is 1, and if we look for it according to the method described in Figure 4 above, what should we do? By traversing the entire array at once, and then deleting the different two numbers at a time, the process is as simple as:

0 1 2 1 1 =>2 1 1=>1

The final 1 is the search.

But if the array is {5, 5, 5, 5, 1}, can you use this idea? Obviously not, we have to find another good idea. Solution Four

Further, given the specificity of the problem, we can save two values when iterating over an array: A candidate that holds a number traversed in the array, and a ntimes that represents the number of occurrences of the current number, where Ntimes is initialized to 1. When we traverse to the next number in the array: If the next number is the same as the previous candidate, then ntimes plus 1, or ntimes minus 1 if the next number is different from the previous candidate, and each time the number of occurrences Ntimes becomes 0, Save the next number with candidate and reset the Ntimes to 1. Until all the numbers in the array have been traversed.

For example, assuming that the array is {0, 1, 2, 1, 1}, the following steps are performed as follows: 1. At the beginning, candidate saves the number 0,ntimes initialized to 1, 2. Then traverses to the number 1, which is different from the number 0, then ntimes minus 1 becomes 0; 3. Because Ntimes becomes 0, candidate saves the next traversed number 2, and Ntimes is reset to 1; 4. Continue traversing to the 4th Digit 1, which is different from the previous candidate saved number 2, so ntimes minus 1 becomes 0; 5. Since Ntimes is again changed to 0, we let candidate save the next traversal to the number 1, and ntimes is reset to 1. The last one to return is the last number to set the Ntimes to 1 1.

The idea is clear, the complete code is as follows:

A represents an array, length represents the array length
int findonenumber (int* A, int length)
{
    int candidate = a[0];
    int ntimes = 1;
    for (int i = 1; i < length; i++)
    {
        if (Ntimes = = 0)
        {
            candidate = a[i];
            Ntimes = 1;
        }
        else
        {
            if (candidate = = A[i])
                ntimes++;
            else
                ntimes--;
        }
    }
    return candidate;
}

For the array {0, 1, 2, 1, 1}, apply the above program to:

I=0,candidate=0,ntimes=1;
i=1,a[1]! = candidate,ntimes--,=0;
i=2,candidate=2,ntimes=1;
i=3,a[3]! = candidate,ntimes--,=0;
I=4,candidate=1,ntimes=1;
if it is 0,1,2,1,1,1, then i=5,a[5] = = candidate,ntimes++,=2; ......
Extrapolate

Enhanced water King: Figure out exactly half the number of occurrences

Analysis: We know that the water King problem: There are n numbers, of which one number appears more than half, which requires the number to be calculated in linear time. So, my question is, the enhanced water King: There are n numbers, one of which is just half the number of times required to find this number in linear time.

Because, obviously, if it happens to be half the story, in this case: 0,1,2,1:

 walk to 0 o'clock, candidate for 0,times 1 times to 1 o'clock, unlike candidate, the Times is reduced to 0 time to 2 o'clock, time 0, then candidate update to 2,times plus 1 times to 1 o'clock, unlike candidate, The Times is reduced to 0; we need to return the next number of saved candidate (number 2), which is the number 1. 

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.