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”),可以将字符串转化为数字。