The title describes a number in the array that appears more than half the length of the array, please 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.Analysis: To find more than half of the number of occurrences of the array, we can use the two methods, one is using the fast row, the array is sorted, and then directly output the number of the middle position of the sorted array. The second is to use Hashmap<integer,integer>,key is the number in the array, value is the number of times it appears in the array, sequentially scans the array, records the number of occurrences of the array, and outputs a key value that is greater than half the value of the array length. The first method code is simple, here is not table, the second method code is as follows:
1 import java.util.ArrayList;2 import java.util.Arrays;3 import java.util.Collection;4 import Java.util.HashMap;5 import Java.util.Set;6 7 Public classSolution {8 Public intMorethanhalfnum_solution (int[] Array) {9 if(array==NULL|| array.length==0){Ten return 0 ; One } A if(array.length==1){ - returnarray[0] ; - } the intmost=0 ; -hashmap<integer,integer> m =NewHashmap<integer,integer>() ; - for(inti =0; i < Array.Length; i++){ - if(!M.containskey (Array[i])) { +M.put (Array[i],1) ; - } + Else{ A inttemp = M.Get(Array[i]); atM.put (Array[i], temp+1) ; - } - - } -Set<integer> A =M.keyset (); - for(inttemp:a) { in if(M.Get(temp) > (array.length/2)){ -most =temp; to } + } - returnMost ; the } *}
"Sword means offer" 19, number of occurrences in the array more than half