Number of occurrences more than half in an array

Source: Internet
Author: User

Idea: Save a number in a value and the number of times, when traversing to the next number, if and save the number of the same number plus 1, or else the number of times minus 1, when the number of 0, then save the next number, and set the number of times to 1, because the number of times to find more than half, then the last number of the

 Public  class morethanhalfnum {         /** * More than half the number of times required * @param nums * @param length * @return  * *     Public Static int FindNum(intNums[],intLength) {if(nums==NULL|| length<=0){return 0; }intresult=nums[0];intTime=1; for(intI=1; i<length;i++) {if(time==0){//equals 0 o'clock, assign the next number to Result,time set to 1Result=nums[i];            time++; }if(Result==nums[i]) {//equal number plus 1time++; }Else{//Unequal number minus 1time--; }        }if(!checkresult (nums, length, result)) {return 0; }returnResult }/** * Determine if the result is correct * @param nums * @param length * @param number * @ret Urn * /     Public Static Boolean Checkresult(intNums[],intLengthintNumber) {intTime=0; for(intI=0; i<length;i++) {if(Number==nums[i])            {time++; }          }Booleanismorethanhalf=true;if(time*2<=length) {//Judge whether the number is more than half the numberismorethanhalf=false; }returnIsmorethanhalf; }}

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.