leetcode-Majority Element

来源:互联网 发布:淘宝店铺扣48分 编辑:程序博客网 时间:2024/06/16 19:35

用哈希表保存出现的次数即可。

public class Solution {    public int majorityElement(int[] nums) {      int max=0,result=0,curLen=0;        HashMap<Integer,Integer> ha=new HashMap<Integer,Integer>();        for(int i=0;i<nums.length;i++)        {                if(!ha.containsKey(nums[i]))        ha.put(nums[i], 1);        else        {        curLen=ha.get(nums[i]);        curLen++;              ha.put(nums[i], curLen);        }        curLen=ha.get(nums[i]);        if(curLen>max)    {    max=curLen;    result=nums[i];    }        }        return result;    }}


0 0
原创粉丝点击