题解 | #数组中出现次数超过一半的数字#

剪绳子

http://www.nowcoder.com/practice/57d85990ba5b440ab888fc72b0751bf8

import java.util.*;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
       HashMap<Integer, Integer> map = new HashMap<>();
        if (array.length==0){return  0;}
        for (int i = 0; i < array.length; i++) {
            if (!map.containsKey(array[i])){
                map.put(array[i],1);
            }
            else {
                Integer integer = map.get(array[i])+1;
                map.put(array[i],integer);
            }
        }

//        int max=0;
        ArrayList<Integer> list = new ArrayList<>();

        Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Integer, Integer> entry = iterator.next();
            Integer value = entry.getValue();
            list.add(value);
        }
        Collections.sort(list);
        System.out.println(list);
        Integer max = list.get(list.size()-1);
        System.out.println(max);

        Iterator<Map.Entry<Integer, Integer>> iterator2 = map.entrySet().iterator();

        while (iterator2.hasNext()) {
            Map.Entry<Integer, Integer> value = iterator2.next();
            if (max == value.getValue()) {
                max=value.getKey();
//                return value.getKey();
            }
        }
        return max;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务