首页 > 其他分享 >数组中出现次数超过一半的数字

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

时间:2022-11-11 21:55:07浏览次数:37  
标签:map return 数字 int 数组 次数 key public

 

 

import java.util.*; public class Solution {     public int MoreThanHalfNum_Solution(int [] array) {         //遍历数组,值标记位key         //新建一个map,map包含这个key,那么对应的value+1,map不包含这个key,那么对应的value设置为1         Map<Integer,Integer> map = new HashMap<Integer,Integer>();         for(int i=0; i<array.length; i++){             Integer key = array[i];             if(!map.containsKey(key)){                 map.put(key,1);             }else{                 int tmp_v = map.get(key);                 map.put(key,tmp_v+1);             }         }         float half = array.length/2;         for(Integer k:map.keySet()){             if(map.get(k)>half){                 return k;             }         }         return -1;     } }

 

标签:map,return,数字,int,数组,次数,key,public
From: https://www.cnblogs.com/northli/p/16882146.html

相关文章