Majority Element 找出一个数组中出现次数最多的元素

来源:互联网 发布:数据库管理dba 编辑:程序博客网 时间:2024/06/05 05:58

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.


public class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer,Integer>map=new HashMap<Integer,Integer>();
        int count=0;
        int res=0;
        for(int i=0;i<nums.length;i++){
            if(map.get(nums[i])==null)  map.put(nums[i],1);
            else    map.put(nums[i],map.get(nums[i])+1);
            if(count<map.get(nums[i]))  count=map.get(nums[i]);
        }
        for(int i=0;i<nums.length;i++){
            if(map.get(nums[i])==count)   res=nums[i];
        }
        return res; //返回语句必须放在这儿,放在上边的for语句里边会爆没有返回语句的错误
    }
}



下边这个解法是参考的别人,因为有Arrays.sort()函数,所以简直是简单,因为题目说了那个出现次数比数组全长的一半还多

public class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}

0 0