Majority Element

来源:互联网 发布:什么是多媒体数据库 编辑:程序博客网 时间:2024/03/29 17:43

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases

思路:就是hashmap count,注意num.length ==1, return num[0];

public class Solution {    public int majorityElement(int[] num) {        if(num.length ==0) return 0;        if(num.length ==1 ) return num[0];                HashMap<Integer,Integer> hashmap = new HashMap<Integer,Integer>();        for(int i=0;i<num.length; i++){            if(hashmap.containsKey(num[i])){                int count = hashmap.get(num[i])+1;                if(count>num.length/2) {                     return num[i];                }                hashmap.put(num[i],count);            }else{                hashmap.put(num[i],1);            }        }        return -1;    }}


0 0
原创粉丝点击