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