In this paper, the algorithm is implemented using Python3
1. Question 11.1 Topic Description:
?? 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.
?? time limit: 1s; space limitation: 32768K
1.2 Idea Description:
?? method One : Create a new dictionary to hold each number and number of occurrences of the number of times, but it is considered that each time the number of existing numbers before the addition of an operation, will first determine whether the condition has been met, if the condition has been met to jump directly, no longer need to continue traversal .
?? method Two : Use res to save the current number, times to save occurrences. Iterate through the array, if the number of traversal is the same as res, then the Times plus one, if different times minus one. When the traversal is complete, the number saved by Res is the desired. For this method we can think of this because the title requirement is more than half the length of the array, so even if the number is unevenly distributed in the array, the number of occurrences is always greater than the sum of the remaining number occurrences. The value of the final times is the difference between the number of occurrences of the number being calculated and the number of other occurrences of the remaining number .
1.3 Program code:
(1) Method one
classSolution:defMorethanhalfnum_solution ( Self, numbers):ifNumbers==[]:return 0 if Len(numbers)== 1:returnnumbers[0] Lens= Len(numbers) Breakflag=Lens/ 2.0Currentcount={} forIinch Range(lens):# If the current number has occurred before, the number plus one ifNumbers[i]inchCurrentcount.keys ():ifCurrentcount[numbers[i]]+ 1 >Breakflag:returnNumbers[i] Currentcount[numbers[i]+= 1 Else: Currentcount[numbers[i]]= 1 return 0
(2) Method two:
classSolution:defMorethanhalfnum_solution ( Self, numbers):if notNumbersreturn 0Res= 0Times= 0 forI, numinch Enumerate(numbers):ifTimes== 0: Res=Num Times= 1 elifNum==Res:times+= 1 Else: Times-= 1 returnResifNumbers.count (RES)> Len(numbers)/ 2 Else 0
"Sword of Offer"---number of occurrences more than half in an array