leetcode 169. Majority Element

leetcode 169. Majority Element

题目

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) {

        int ret=0;
        int retnum=0;
        //放入队列
        ArrayList<Integer> numsList=new ArrayList<Integer>();
        for(int i=0;i<nums.length;i++){
            numsList.add(nums[i]);
        }

        //转存到HashMap中进行计数
        HashMap<Integer,Integer> elementsCounts=new HashMap<Integer,Integer>();
        for(Integer a:numsList){

            Integer n=elementsCounts.get(a);
            if(n==null){
                elementsCounts.put(a,1);
            }else{
                elementsCounts.put(a,n+1);
            }
        }

        //找到出现次数最多的那个数
        Iterator it=elementsCounts.keySet().iterator();    
        while(it.hasNext()){    
              Integer key;    
              Integer value;    
              key=Integer.parseInt(it.next().toString());  
              value=elementsCounts.get(key);    
              if(value>retnum){
                  retnum=value;
                  ret=key;
              }

        }


        return ret;

    }
}

补充

1. ArrayLis和iterator()

ArrayList<Integer> list=new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);

Iterator it=list.iterator( );  
while(it.hasNext())
{   
    Integer a=Integer.parseInt(it.next().toString());
//以下进行各种操作
}

2.HashMap和iterator()

HashMap<String ,Integer> map=new HashMap<String ,Integer>();
map.put("a", 1);
map.put("b", 3);
map.put("c", 5);

Iterator it=map.keySet().iterator( );  
while(it.hasNext())
{   
    String key;
    Integer value;
    key=it.next().toString();
    value=map.get(key);
    //以下进行各种操作
}

小结

1,集合类中都是不可以存放基本数据类型的;集合类中存放的必须是对象,即Object的子类;
2,集合类都是有迭代方法的,便于使用迭代器对集合类进行遍历;
3 , HashMap的put( key,value),是可以根据key值,对value进行更新的;
4,Integer.parseInt(” 1”),可以将字符串转化为数字。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值