美文网首页
28、数组中出现次数超过一半的数字

28、数组中出现次数超过一半的数字

作者: quiterr | 来源:发表于2017-09-02 21:45 被阅读0次

    题目描述
    数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

    这题的解法不止一种,我选择一种自己顺手的,但是map的用法(比如遍历)真的容易忘。

    import java.util.*;
    
    public class Solution {
        public int MoreThanHalfNum_Solution(int [] array) {
            Map<Integer,Integer> map = new HashMap<>();
            for(int i=0; i<array.length; i++){
                Integer tmp = map.get(array[i]);
                if(tmp==null){
                    tmp=0;
                }
                map.put(array[i],tmp+1);
            }
            for(Map.Entry<Integer,Integer> entry: map.entrySet()){
                if(entry.getValue()>(array.length/2)){
                    return entry.getKey();
                }
            }
            return 0;
        }
    }
    

    2017.6.2 第二次做,要找的数字必定出现在中间

    import java.util.*;
    
    public class Solution {
        public int MoreThanHalfNum_Solution(int [] array) {
            if(array.length == 0){
                return 0;
            }
            Arrays.sort(array);
            int ret = array[array.length/2];
            int count = 0;
            for(int i=0; i<array.length; i++){
                if(array[i] == ret){
                    count++;
                }
            }
            if(count>array.length/2){
                return ret;
            }
            return 0;
        }
    }
    

    相关文章

      网友评论

          本文标题:28、数组中出现次数超过一半的数字

          本文链接:https://www.haomeiwen.com/subject/carhwttx.html