如何使用Java Collections框架找到最常见的元素? 我有一个整数数组,需要有效地找到k最频繁的元素。理想情况下,解决方案应使用Java集合在O(n log K)时间复杂性中起作用。对所有元素进行排序...

问题描述 投票:0回答:0
N

时效率低下的时间。我正在寻找一种更优化的方法。 我尝试了什么以及我的期望: i首先使用hashmap

来计算每个元素的频率。然后,我使用collections.sort()

对条目进行了排序,但是此方法在

o(n log n)时间中运行,这不是最佳的。我使用Priorityqueue(Minheap)或Treemap

进行了探索,但我正在努力正确实施它们。具体而言,我不确定如何在频率图上迭代时如何有效地维护k个最频繁的元素。

我尝试的是什么(代码): import java.util.*; public class KMostFrequent { public static List<Integer> topKFrequent(int[] nums, int k) { Map<Integer, Integer> frequencyMap = new HashMap<>(); for (int num : nums) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } List<Map.Entry<Integer, Integer>> entryList = new ArrayList<>(frequencyMap.entrySet()); entryList.sort((a, b) -> b.getValue() - a.getValue()); // Sorting in descending order List<Integer> result = new ArrayList<>(); for (int i = 0; i < k; i++) { result.add(entryList.get(i).getKey()); } return result; } public static void main(String[] args) { int[] nums = {1, 1, 1, 2, 2, 3}; int k = 2; System.out.println(topKFrequent(nums, k)); // Expected Output: [1, 2] } } 使用此代码: 排序步骤(entryList.sort())采用o(n log n)

,这对大

N

效应效率低下。我相信使用
minheap(Priorityqueue)或
treemap

可以提高性能。 从事,我已经搜索了现有的解决方案,但主要是基于Collections.sort()

的方法,这些方法不符合所需的效率。一些帖子暗示使用Minheap,但我在迭代地图时努力保持正确的堆结构。

import java.util.*;

public class KMostFrequent {
    public static List<Integer> topKFrequent(int[] nums, int k) {
        // Step 1: Count the frequency of each element
        Map<Integer, Integer> frequencyMap = new HashMap<>();
        for (int num : nums) {`enter code here`
            frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
        }

        // Step 2: Use a MinHeap (PriorityQueue) to keep the top K elements
        PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(
            Comparator.comparingInt(Map.Entry::getValue) // MinHeap based on frequency
        );

        // Step 3: Iterate over the frequency map and maintain only the top K elements
        for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
            minHeap.offer(entry);
            if (minHeap.size() > k) {
                minHeap.poll(); // Remove the least frequent element
            }
        }

        // Step 4: Extract elements from the MinHeap
        List<Integer> result = new ArrayList<>();
        while (!minHeap.isEmpty()) {
            result.add(minHeap.poll().getKey());
        }
        Collections.reverse(result); // Optional: to maintain descending order of frequency

        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1, 1, 1, 2, 2, 3};
        int k = 2;
        System.out.println(topKFrequent(nums, k)); // Expected Output: [1, 2]
    }
}

    
	

java sorting search collections hashmap
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.