首页 > 其他 > 详细

Majority Element

时间:2015-01-08 00:42:26      阅读:329      评论:0      收藏:0      [点我收藏+]

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]; 
    }
};

 

Majority Element

原文:http://www.cnblogs.com/mrpod2g/p/4209711.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!