"The point of the sword" question 29: Number of occurrences in an array more than half

Source: Internet
Author: User

9 of Arrays {1,2,3,2,2,2,5,4,2  252.

Many people will think of this array to sort the question. In the sorted array, the number in the middle position is the number that exceeds half the length of the array. Because we need to sort the arrays, the total time complexity is O (N*LGN).

Solution two, using the array features to find O (N) algorithm:

The number of numbers to be found in the topic is more than half the length of the array, meaning that it appears more often than any other number.

So we can consider saving two values when iterating over an array: One is a number in an array, and the other is the number of times.

When we traverse to the next number,

If the next number is the same as the current number we saved, the number of times is 1;

If it is different from the current number we save, the number will be reduced by 1;

When the number of times is reduced to 0, we change the saved number to the position where the current traverse is, changing the number of times to 1.

The complete code is as follows:

1 intMorethanhalfnum (int*arr,intlen)2 {3     intresult = arr[0];4     intCount =1;5 6      for(inti =1; i < Len; ++i)7     {8         if(Arr[i] = =result)9Count + +;Ten         Else if(Count = =0) One         { Aresult =Arr[i]; -Count =1; -         } the         Else -Count--; -     } -     returnresult; + } -  + intMainintargcChar*argv[]) A { at     intarr[5] = {1,0,1,2,1}; -  -     intnum = Morethanhalfnum (arr,5); -printf"The num is:%d\n", num); -  -     return 0; in}
View Code
Time complexity: Because the array is traversed only once, the time complexity is O (n).

The end of this article.

"The point of the sword" question 29: Number of occurrences in an array more than half

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.