首页 > 代码库 > 每天一道LeetCode--169.Majority Elemen
每天一道LeetCode--169.Majority Elemen
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.
package cn.magicdu; import java.util.HashMap; import java.util.Map; public class _169_Majority_Element { /*public static void main(String[] args) { _169_Majority_Element e=new _169_Majority_Element(); int arr[]={2,2,2,3,4,5,5,6,6,6,6,6,6,6,6}; System.out.println(e.majorityElement(arr)); }*/ public int majorityElement(int[] nums) { Map<Integer,Integer> map=new HashMap<>(); int size=nums.length; for(int i=0;i<size;i++){ if(map.containsKey(nums[i])){ map.put(nums[i],map.get(nums[i])+1); }else{ map.put(nums[i],1); } if(map.get(nums[i])+1>size/2){ return nums[i]; } } return 0; } }
每天一道LeetCode--169.Majority Elemen
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。