9 of Arrays {1,2,3,2,2,2,5,4,2 252.
Many people will think of this array to sort the question. In the sorted array, the number in the middle position is the number that exceeds half the length of the array. Because we need to sort the arrays, the total time complexity is O (N*LGN).
Solution two, using the array features to find O (N) algorithm:
The number of numbers to be found in the topic is more than half the length of the array, meaning that it appears more often than any other number.
So we can consider saving two values when iterating over an array: One is a number in an array, and the other is the number of times.
When we traverse to the next number,
If the next number is the same as the current number we saved, the number of times is 1;
If it is different from the current number we save, the number will be reduced by 1;
When the number of times is reduced to 0, we change the saved number to the position where the current traverse is, changing the number of times to 1.
The complete code is as follows:
1 intMorethanhalfnum (int*arr,intlen)2 {3 intresult = arr[0];4 intCount =1;5 6 for(inti =1; i < Len; ++i)7 {8 if(Arr[i] = =result)9Count + +;Ten Else if(Count = =0) One { Aresult =Arr[i]; -Count =1; - } the Else -Count--; - } - returnresult; + } - + intMainintargcChar*argv[]) A { at intarr[5] = {1,0,1,2,1}; - - intnum = Morethanhalfnum (arr,5); -printf"The num is:%d\n", num); - - return 0; in}View Code
Time complexity: Because the array is traversed only once, the time complexity is O (n).
The end of this article.
"The point of the sword" question 29: Number of occurrences in an array more than half