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. Analytic: method One: This problem is the most low solution is, with a hashmap to save up, and finally check if there are more than half of the number, then choose two different delete, the last number is definitely more than half of the Number. Method Two: the previous traversal, each encounter is not 0 of the number, find him behind a not 0 and not equal to his number, and set to 0. Finally find a not for 0, traverse to see if this number is more than half the number of occurrences, if it is to return, not to return 0 method three first number as a reference count of 1, from his back, find a and his inconsistent count-1,count for 0 then jump to the next for reference, If the same flag bit count++, continue to run repeatedly, the final reference is probably the number, and then go through the total number is more than half method three very ingenious, the code is as Follows:
 public classSolution { public intMorethanhalfnum_solution (int[] Array) {        intLength=array.length; if(array==NULL|| Length<=0){            return0; }                intResult=array[0]; intTimes=1;  for(inti=1;i<length;i++){            if(times==0) {result=array[i]; times=1; }Else{                if(array[i]==Result) { times++; }Else{ times--; } }} Times=0;  for(inti=0;i<length;i++){            if(result==array[i]) { times++; }       }                   if(times*2<Length) {result=0; }       returnresult; }}

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.