74. More than half of the numbers appear in the array (array)
Question: If a number in the array appears more than half the length of the array, find the number.
Idea: Divide and conquer algorithms use the same pair to keep a different pair and separate the numbers.
/* 74. A number (array) with more than half of the number of occurrences in the array. The number of occurrences of a number in the array exceeds half of the length of the array. * // Train of thought: the Splitting Algorithm leaves a different pair of numbers for separate comparison # include <stdio. h> # include <stdlib. h> int find (int * In, int Len) {If (LEN = 0) {return 0;} If (LEN % 2 = 1) // odd, add a round to compare all {int I = 0; int COUNT = 0; for (I = 0; I <Len; I ++) {If (in [I] = in [Len-1]) Count ++;} If (count> (len-1)/2) {return in [Len-1] ;}} int * remain = (int *) malloc (LEN/2 * sizeof (INT); // cannot be released ..?? Int remainlen = 0; For (INT I = 0; I <Len; I ++ = 2) {If (in [I] = in [I + 1]) {remain [remainlen ++] = in [I] ;}} return find (remain, remainlen);} int main () {int A [10] = {5, 6, 7, 8, 5, 5, 5, 5, 5, 6}; int ans = find (A, 10); Return 0 ;}
My code has a big problem and the memory I opened cannot be released. Looking at the answer on the internet, I found that I don't have to bother writing this...
Online thinking: http://www.oschina.net/code/snippet_859732_22139
Each time two different numbers are taken out, the number that is repeated in the remaining number must be larger than other numbers, reducing the scale. If two different numbers are deleted at a time, the highest frequency in the remaining number is more than half the frequency. Repeat the process and the rest is all the same number. The time complexity is O (n)
int findmostappear(int *a,int len) { int candidate=0,count=0; for(int i=0;i<len;i++) { if(count==0) { candidate=a[i]; count=1; } else { if(candidate==a[i]) count++; else count--; } } return candidate; }