Number of occurrences more than half in an array

Source: Internet
Author: User

The title describes a number in the array that appears more than half the length of the array, please find this number. For example, enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears in the array 5 times, which exceeds half the length of the array, the output is 2. Output 0 If it does not exist. I started my own idea is to use the bucket sorting method, each occurrence of the number of markers and increase 1, and finally traverse some of the array of the number of occurrences of more than 2 output. But it doesn't pass the test data.
Class Solution {public:    int morethanhalfnum_solution (vector<int> numbers) {    if (numbers.size () ==0) return 0;        Sort (Numbers.begin (), Numbers.end ());    int min=numbers[0];        int Max=numbers[numbers.size ()-1];        int k=max-min;        int t;        Vector<int> Book (k+1,0);                for (int i=0;i<numbers.size (); i++) {        book[numbers[i]]++;        }                for (int j=0;j<k;j++) {            if (book[j]> (Numbers.size ()/2)) {                t=book[j];                break;            }                        }              return t;    }          ;

  

Check out the other online ideas:

What is the num that is obtained at the end of the first for loop? If the number in this array is greater than half the length of the array, then this num must be the number, because all the numbers in the array that are not num are bound to be covered by this number, so the last number to get is Num. However, if there are no more than half the number of arrays in this array, then this num is an indeterminate value, which is why after you find num, you have to do another loop to verify that the number of occurrences is greater than half the length of the array.

Class Solution {public:    int morethanhalfnum_solution (vector<int> numbers) {    int n=numbers.size ();        if (n==0) return 0;        int num=numbers[0],count=1;        for (int i=1;i<n;i++) {            if (numbers[i]==num) count++;            else count--;            if (count==0) {                num=numbers[i];                count=1;            }        }                count=0;        for (int i=0;i<n;i++) {if (numbers[i]== num) count++;}        if (count * 2 >n) return num;        return 0;    }           };

  

Ideas: after the array is sorted, it must be the number in the middle of the array if the number of matching criteria exists .。 (e.g. 1,2,2,2,3; or 2,2,2,3,4; 2,3,4,4,4, etc.) This method is easy to understand, but due to the fact that it involves the fast sort, its time complexity is O (NLOGN)is not optimal;
Class Solution {Public:    int morethanhalfnum_solution (vector<int> numbers)      {        //because of the sort, time complexity O (NLOGN), not the best          if (Numbers.empty ()) return 0;                  sort (Numbers.begin (), Numbers.end ()); Sort, take the middle number of the array         int middle = numbers[numbers.size ()/2];                  int count=0; Occurrences         for (int i=0;i<numbers.size (); ++i)          {            if ( Numbers[i]==middle) ++count;        }            &nbSp;     return (Count>numbers.size ()/2)? Middle:  0;    }};

  

Idea two: If there are numbers that match the criteria, then it appears more times than all other numbers. Save two values when iterating through an array: One is a number in an array, and the other is the number of times. When traversing the next number, if it is the same as the previously saved number, the number of times is 1, otherwise the number is reduced by 1, and if the number is 0, the next number is saved and the number is set to 1. After the traversal is completed, the saved numbers are the desired. Then judge if it meets the criteria.
Class Solution {Public:    int morethanhalfnum_solution (vector<int> numbers)      {        if (Numbers.empty ()) return 0;                  //iterates through each element and records the number of times, and if the previous element is the same, The number of times plus 1, or the number of times minus 1        int result = numbers[0];         int times = 1; Number of                  for ( int i=1;i<numbers.size (); ++i)         {             if (Times = = 0)              {                 //Update result value is the current element, and the number of occurrences is 1                 result = numbers[i];                 times = 1;             }            else if ( Numbers[i] = = result)             {                 ++times; The same adds 1            }             else             {                - -times; The difference is reduced 1                             }        }                  //Determines whether result meets the criteria, i.e. the number of occurrences is greater than half the length of the array         times = 0;        for ( int i=0;i<numbers.size (); ++i)         {             if (numbers[i] = = result) ++times;         }                  return (Times > Numbers.size ()/2)? result:0;    }};

  

Number of occurrences more than half in an array

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.