在数组中找到出现次数大于n/k的数

时间:2021-10-14
本文章向大家介绍在数组中找到出现次数大于n/k的数,主要包括在数组中找到出现次数大于n/k的数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

链接

给定一个整型数组arr,再给定一个整数k,打印所有出现次数大于n/k的数,如果没有这样的数,请打印”-1“。

import java.util.*;

public class Main {

    private static void reduceOne(Map<Integer, Integer> candidateMap) {
        Iterator<Map.Entry<Integer, Integer>> iterator = candidateMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Integer> next = iterator.next();
            if (next.getValue() == 1) {
                iterator.remove();
            } else {
                next.setValue(next.getValue() - 1);
            }
        }
    }

    private static List<Integer> solve(int[] arr, int k) {
        int n = arr.length;

        Map<Integer, Integer> candidateMap = new HashMap<>();

        for (int num : arr) {
            if (candidateMap.containsKey(num)) {
                candidateMap.put(num, candidateMap.get(num) + 1);
            } else {
                if (candidateMap.size() < k) {
                    candidateMap.put(num, 1);
                } else {
                    reduceOne(candidateMap);
                }
            }
        }

        List<Integer> ret = new ArrayList<>();
        Map<Integer, Integer> countMap = new HashMap<>();

        for (int num : arr) {
            if (candidateMap.containsKey(num)) {
                Integer count = countMap.getOrDefault(num, 0);
                if (count == n / k) {
                    ret.add(num);
                }
                countMap.put(num, count + 1);

            }
        }
        return ret;
    }

    private static void print(List<Integer> ret) {
        if (ret.size() == 0) {
            System.out.println(-1);
            return;
        }

        StringBuilder sb = new StringBuilder();
        for (int num : ret) {
            sb.append(num).append(" ");
        }
        System.out.println(sb.toString().trim());
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            int k = in.nextInt();
            int[] arr = new int[n];
            for (int i = 0; i < n; ++i) {
                arr[i] = in.nextInt();
            }
            List<Integer> ret = solve(arr, k);
            print(ret);
        }
    }
}
心之所向,素履以往 生如逆旅,一苇以航

原文地址:https://www.cnblogs.com/tianyiya/p/15405507.html