一个数组,“支配者”是在数组中出现频率超过一半的整数, 例如[3,4,3,2,-1,3,3,3]数值“3”出现过5次,5除以8大于0.5
所以数值“3”是一个支配者; 而在这个数组中的支配者出现在数组下标[0,2,4,6,7]
写一个函数,在给定的整数数组中找出支配者所在的任意一个数组下标,如果一个数组中没有支配者返回-1;
要求:使用集合实现.
- package Package;
- import java.util.*;
- /**
- * @author atlightsgh@gmail.com
- * 2008-11-26
- */
- public class temp {
- public static void main(String[] args) {
- int[] array = { 1, 2, 7, 3, 3, 4, 4, 5, 6, 3, 2, 3, 3, 3, 3, 3, 3 };
- System.out.println(FindMaster(array));
- }
- // 查找数组中的支配者,并返回其道次在数组中出的下标.算法复杂度O(n)
- // 使用集合实现
- static int FindMaster(int array[]) {
- HashMap<Integer, Integer> counter = new HashMap<Integer, Integer>();
- // 数组所有元素存入hashmap.并在存入时统计其个数
- for (int e : array) {
- Integer v = counter.get((Integer) e);
- if (v == null)
- counter.put(e, 1);
- else
- counter.put(e, v + 1);
- }
- Integer maxcounterK = 0;
- Integer maxcounterV = 0;
- // 寻找出现次数最多的元素和其出现次数
- for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
- Integer entryV = entry.getValue();
- if (maxcounterV < entryV) {
- maxcounterV = entryV;
- maxcounterK = entry.getKey();
- }
- }
- // 查找支配者首次出现的下标
- if (maxcounterV > array.length / 2)
- for (int i = 0; i < array.length; i++)
- if (array[i] == maxcounterK)
- return i;
- return -1;
- }
- }