每天一道LeetCode--169.Majority Elemen

Posted 华裳绕指柔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了每天一道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的主要内容,如果未能解决你的问题,请参考以下文章

每天一道Rust-LeetCode(2019-06-05)

每天一道Java题[3]

每天一道Rust-LeetCode(2019-06-11)

每天一道Rust-LeetCode(2019-06-07)

每天一道Rust-LeetCode(2019-06-06)

每天一道leetcode-110平衡二叉树