1. Question
找数组中的大多数元素,即元素个数超过一般的那个元素
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
2. Solution
排序后中位数即为所求,该问题可转化为求中位数问题。
2.1 O(nlogn)
先排序,那么中位数即为所求。
public class Solution { public int majorityElement(int[] num){ Arrays.sort(num); return num[num.length/2]; } }
或者,利用快排思想,求中位数。
public class Solution { //similar to quicksort, every time you pick a branch to find. public int partition( int[] num, int start, int end ){ if( num == null ) return 0; int k = num[start]; int i = start+1; int j = end; while( i<=j ){ for( ; i<=j && num[i]<=k; i++ ); for( ; i<=j && num[j]>k; j-- ); if( i<=j ){ int temp = num[j]; num[j] = num[i]; num[i] = temp; i++; j--; } else break; } return i-1; } public int majorityElement( int[] num){ int start = 0; int end = num.length-1; int medium = num.length/2; while( true ){ int i = partition(num, start, end); if( i==medium ) break; else if( i<medium ) start = i+1; else if( i>medium ) end = i-1; } return num[medium]; } }
2.2 O(n)
采用hashtable,实际计算元素个数。效果不如排序好,因为操作复杂,运算量大,所以实际效果不好。
import java.util.Hashtable; public class Solution { //using hashtable, O(n) public int majorityElement(int[] num){ Hashtable<Integer, Integer> elements = new Hashtable<Integer, Integer>(); int medium = num.length/2; for( int i=0; i<num.length; i++ ){ if( elements.containsKey(num[i]) ){ int val = elements.get(num[i]).intValue()+1; elements.replace(num[i], val); } else elements.put(num[i], 1); if( elements.get(num[i]).intValue() > medium) return num[i]; } return -1; } }