寻找数组支配者下标

一个数组,“支配者”是在数组中出现频率超过一半的整数, 例如[3,4,3,2,-1,3,3,3]数值“3”出现过5次,5除以8大于0.5
所以数值“3”是一个支配者; 而在这个数组中的支配者出现在数组下标[0,2,4,6,7]


写一个函数,在给定的整数数组中找出支配者所在的任意一个数组下标,如果一个数组中没有支配者返回-1;

要求:使用集合实现.

 

  1. package Package;
  2. import java.util.*;
  3. /**
  4.  * @author atlightsgh@gmail.com
  5.  * 2008-11-26
  6.  */
  7. public class temp {
  8.     public static void main(String[] args) {
  9.         int[] array = { 12733445632333333 };
  10.         System.out.println(FindMaster(array));
  11.     }
  12.     // 查找数组中的支配者,并返回其道次在数组中出的下标.算法复杂度O(n)
  13.     // 使用集合实现
  14.     static int FindMaster(int array[]) {
  15.         HashMap<Integer, Integer> counter = new HashMap<Integer, Integer>();
  16.         // 数组所有元素存入hashmap.并在存入时统计其个数
  17.         for (int e : array) {
  18.             Integer v = counter.get((Integer) e);
  19.             if (v == null)
  20.                 counter.put(e, 1);
  21.             else
  22.                 counter.put(e, v + 1);
  23.         }
  24.         Integer maxcounterK = 0;
  25.         Integer maxcounterV = 0;
  26.         // 寻找出现次数最多的元素和其出现次数
  27.         for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
  28.             Integer entryV = entry.getValue();
  29.             if (maxcounterV < entryV) {
  30.                 maxcounterV = entryV;
  31.                 maxcounterK = entry.getKey();
  32.             }
  33.         }
  34.         // 查找支配者首次出现的下标
  35.         if (maxcounterV > array.length / 2)
  36.             for (int i = 0; i < array.length; i++)
  37.                 if (array[i] == maxcounterK)
  38.                     return i;
  39.         return -1;
  40.     }
  41. }

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值