More than half of the array data

topic

  • There are a number of array number that appears more than half the length of the array, find this number.
    For example, a length of the input array 9 {1,2,3,2,2,2,5,4,2}.
    Since the number 2 appears five times, more than half the length of the array in the array, the output 2. If there is 0 output.

A thought

Using HashMapthe method, through the entire array, record valueand its corresponding countvalue.

  //使用HashMap
    public int MoreThanHalfNum_Solution(int [] array) {
        HashMap<Integer,Integer> hashMap = new HashMap<>();

        for(int i=0;i<array.length;i++){
            Integer count = hashMap.get(array[i]);
            if(count!=null){
                hashMap.put(array[i],count+1);
            }else{
                hashMap.put(array[i],1);
            }
        }
       Set<Integer> set =  hashMap.keySet();
        for(Integer key:set){
            if(hashMap.get(key)>array.length/2){
                return key;
            }
        }

        return 0;
    }

Ideas two

Thinking two: If the number has qualified a number, and it appears even more than the number of all the other numbers appear.
Save when traversing an array of two values: one is a numeric array, one number.
When traversing the next number, if it is previously stored in the same figure, plus the number 1 or decremented by 1;
if the number is 0, the next number is saved, and the number is set to 1. After traversing the saved numbers is also desired.
And then determine whether it meets the conditions can be.


    public int MoreThanHalfNum_Solution1(int [] array){

            int value = 0;
            int count = 0;
            for(int i=0;i<array.length;i++){
                //若count为0,则保存下一个数字
                if(count==0){
                    value=array[i];
                    count++;
                }else {
                    if(array[i]==value)
                    {count++;}
                    else{
                        count--;
                    }
                }

            }

        // 判断result是否符合条件,即出现次数大于数组长度的一半
        int times = 0;
        for(int i=0;i<array.length;++i)
        {
            if(array[i] == value) ++times;
        }

        return (times >array.length/2)?value:0;


    }

Published 224 original articles · won praise 22 · views 20000 +

Guess you like

Origin blog.csdn.net/ZHOUJIAN_TANK/article/details/105081504