Given an array of length N, find that appear more than n / number 2, n / 3, the required time complexity O (n), the spatial complexity is O (1)

  Appear to discuss a number greater than the number n / 2, if such number exists, then the number of occurrences of the number of times greater than the sum of the number of occurrence of the other.

In the array A, we define two sets of data a1, a2. A1 is a set number of occurrences of the number is greater than n / 2 in, a2 number set for the rest of the composition. For array

A elements a, b, assumed that a is not equal B, then there are two cases, namely: a part of a1, b belong A2; a belonging a2, b belong a2. In both cases, such as

If the a, b is removed from the array A, the set size is still larger than the a1 and a2. According to this idea, we have the following code:

   int m;
    int count = 0;
    for (auto num : nums) 
   { 
     // initial time to. 1
IF ( 0 == COUNT) { m = num; ++count; } the else {
       // if we add an equal unequal to simultaneously remove
IF (m == NUM) ++ COUNT; the else - COUNT; }
  }

 

Then find the number of times greater than for 1/3, we present a maximum of two such numbers n, m. Or the ratio of n m and the remaining portion that is any one of 1: 1, which is greater than the number of conversions for the sake of 1/2. code show as below:

int m, n; // presence of up to two times more than a third element appears 
    int cm & lt, CN; // corresponding to m and n are statistically 
    for (Auto NUM: the nums) {
         IF (cm & lt == 0 || NUM = = m) {
            m = num;
            ++ cm;
        }
        else  if (c == 0 || whether == n) {
            n = num;
            ++ CN;
        }
        else {
            --cm;
            --cn;
        }
    }

Can be simply understood as if never more than 1/3 of that portion of the data to remove a number, n, m corresponding to each data set to remove a number, n, m corresponding to the data set size is greater than the third condition it will not change.

 

Guess you like

Origin www.cnblogs.com/z1141000271/p/11773775.html