Given an array of size n, find the majority element. The majority element is the element, the appears more than times ? n/2 ? .
Assume that the array was non-empty and the majority element always exist in the array.
Given an array, the element in which the weight is the largest, (the element appears more than half the number of times).
Intuitive ideas, HashMap, very slow
Public classSolution { Public intMajorityelement (int[] nums) {Map Map=NewHashmap<integer, integer>(); intLen =nums.length; if(len = = 1){ returnNums[0]; } for(intnum:nums) { if(Map.containskey (num)) {intCount = (int) map.get (num); if((count + 1) > LEN/2){ returnnum; } Else{map.put (num, Count+ 1); } } Else{map.put (num,1); } } return-1; }}
Discuss above see this question very perfect summary:
1. Sorting sort
Public int majorityElement1 (int[] nums) { arrays.sort (nums); return NUMS[NUMS.LENGTH/2];}
2, HashMap
3. Moore's voting algorithm (best algorithm)
Very ingenious, time O (n), Space O (1), is to record the current element and the current element of the "winning" number (more than other elements).
Public int majorityElement3 (int[] nums) { int count=0, ret = 0; for (int num:nums) { if (count==0) = num; if (num!=ret) count--; Else Count++ ; } return ret;}
4, bit arithmeticBit manipulation
By recording the numbers on each one, it is better to compare the third algorithm to the result.
Public intMajorityelement (int[] nums) { int[] bit =New int[32]; for(intnum:nums) for(inti=0; i<32; i++) if((Num>> (31-i) & 1) = = 1) Bit[i]++; intRet=0; for(inti=0; i<32; i++) {Bit[i]=bit[i]>nums.length/2?1:0; RET+ = bit[i]* (1<< (31-i)); } returnret;}
Leetcode 169. Majority Element to find the most occurrences of the number---------Java