Title:
If there is a number in the array that appears more than half the length of the array, 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.
parsing:
The first thing I want to see in this question is to sort the array first, and then iterate over the number of test instructions that are in the sorted array. This method is feasible, but this method is too obvious, and the sorting time complexity is greater than O (n), feeling the interviewer will definitely not agree. So I think of the number of i+1 and the number of numbers to compare, if the same note this number and the counter plus one, the difference is minus one, when the counter is zero, the number is re-recorded; once traversed, if the counter is zero there is no such number, otherwise there may exist, and then traverse again, Compares the number of records to all the numbers in the array, and finally returns the number if the same number is greater than the array length, and returns 0, the time complexity of this method is O (n);
I have written down the code for both methods to share with you.
Method one code:
1 intMorethanhalfnum_solution (int*arr,intlen)2 {3 intI,j,flag =1, Count =1;4 for(i=0; i<len-1; i++)//to sort an array5 {6 for(j=0; j<len-1-I.; J + +)7 {8 if(arr[j]>arr[j+1])9 {Ten intTMP =Arr[j]; OneARR[J] = arr[j+1]; Aarr[j+1] =tmp; -Flag =0; - } the } - if(flag) - Break; - } + for(i =0; i<len; i++)//iterate over to find out if there are numbers that match test instructions - { + if(Arr[i] = = arr[i+1]) A { atj =i; -count++; - if(Count> (len>>1)) - { - returnArr[j]; - } in } - Else to { +Count =1; - } the } * return 0; $}
Method two code:
1 intMorethanhalfnum_solution (int*arr,intlen)2 {3 inti =1;4 intK =0;5 intCount =1;6 while(i<len)7 {8 if(arr[i]==Arr[k])9 {TenK = i;//record the current location Onecount++; A } - Else - { thecount--;//different counter minus 1 - if(Count = =0) - { -Count =1; +K =i; - } + } Ai++; at } - if(count) - { -Count =0; - for(i=0; i<len; i++) - { in if(arr[k]==Arr[i]) -count++; to } + if(count>len/2) - returnArr[k]; the Else * return 0; $ }Panax Notoginseng Else - return 0; the}
CSDN Blog Address: http://blog.csdn.net/qq_38646470
The number of occurrences in the array of the "offer of swords" exceeds half the length of the array