Majority Element

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 ar

Java:

public class Solution {
    public int majorityElement(int[] num) {
        Map<Integer,Integer>num_map=new HashMap<Integer,Integer>();
        int array_size=num.length;
        for(int i=0;i<array_size;i++){
            if(!num_map.containsKey(num[i])){
                num_map.put(num[i],1);
            }
            else{
                int temp=num_map.get(num[i]);
                num_map.put(num[i],temp+1);
            }
        }
        Set<Integer>keys=num_map.keySet();
        int count=0;
        int result=0;
        for(int key:keys){
            if(num_map.get(key)>count){
                count=num_map.get(key);
                result=key;
            }
        }
        return result;
    }
}

C++

class Solution {
public:
    int majorityElement(vector<int> &num) {
        int n = num.size();  
        sort(num.begin(),num.end());  
        return num[n/2]; 
    }
};
原文地址:https://www.cnblogs.com/mrpod2g/p/4209711.html