牛客_数组中出现次数超过一半数组长度的元素

题目描述

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

思路:

采用使用hashmap的方式,其中一个作为接收数组元素的标识,另一个作为该元素出现的次数

可以直接在hashmap中判断元素是否超过总长度的一半,不需要再次遍历数组,因为,如果一个数组中只可能有一个元素的长度超过总长度的一半,不会出现两个,找到的肯定是唯一一个

/**
 * @ Author zhangsf
 * @CreateTime 2019/2/25 - 10:45 AM
 */
package com.bjut;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Solution {
    public static void main(String[] args) {
        int test1[]={1,2,3,2,2,2,5,4,2};
        int test2[]={1};

        int h1 =MoreThanHalfNum_Solution(test1);
        int h2 =MoreThanHalfNum_Solution(test2);
        System.out.println("测试输出最终出现次数超过数组长度一半的元素-test1----"+h1);
        System.out.println("测试输出最终出现次数超过数组长度一半的元素-test2----"+h2);

    }
    public static int MoreThanHalfNum_Solution(int [] array) {
        int i= array.length;
        if(array==null||i==0){
            return 0;
        }
        if (i==1){return  array[0];}
        //使用hashmap来标记数组中出现的数字和这个数字出现的次数
        //当这些数字出现了次数超过了i/2就输出标记的数字
        HashMap<Integer,Integer> map =new HashMap<Integer,Integer>();
        for(int j=0;j<i;j++){
            //当hashmap中没有出现第j个元素就直接将这个元素作为Key放入到hashmap中并将value置为1
            if(!map.containsKey(array[j])){
                map.put(array[j],1);
            }else{
                //使用count来标记第j个元素在hashmap中出现的次数
                int count =map.get(array[j]);
                //当hashmap中存在第j个元素就将这个元素出现的次数+1
                map.put(array[j],++count);
                //判断元素出现次数超过总数的一半就直接返回
          if(count*2>i){
               return array[j];
           }
            }

        }
//        Iterator iter = map.entrySet().iterator();
//        while(iter.hasNext()){
//            Map.Entry entry = (Map.Entry)iter.next();
//            Integer key =(Integer)entry.getKey();
//            Integer val = (Integer)entry.getValue();
//            if(val*2>i){
//                return key;
//            }
//        }
        return 0;
    }
}

 

牛客_数组中出现次数超过一半数组长度的元素