简体   繁体   English

时间复杂度 O(nlogn) 是多少? 我错过了什么吗?

[英]How is the the time complexity O(nlogn)? Am I missing something?

I have a function for the following problem statement:我有以下问题陈述的函数:

Remove k least frequent elements to make the remaining ones as least unique ints set.删除 k 个最不频繁的元素,使剩余的元素成为最不唯一的整数集。

How is the Time Complexity O(nlogn)?时间复杂度 O(nlogn) 怎么样? I am calculating O(n + nlogn).我正在计算 O(n + nlogn)。

public class KRemoval {
    public static int solution(int k, ArrayList<Integer> arr, int num) {
        Map<Integer, Integer> map = new HashMap();
        for (int a : arr)
            map.put(a, map.getOrDefault(a, 0) + 1);

        PriorityQueue<Integer> q = new PriorityQueue((a, b) -> map.get(a) - map.get(b));
        for (int key : map.keySet())
            q.offer(key);

        while (k > 0 && !q.isEmpty())
            k -= map.get(q.poll());

        return k < 0 ? q.size() + 1 : q.size();
    }
}

n + n*log(n) can be seen as the sum of two distinct functions, that are f(n) = n and g(n) = n*log(n) , respectively. n + n*log(n)可以看作是两个不同函数的总和,分别是f(n) = ng(n) = n*log(n) The first function is slower than the second, since the limit lim_{n -> +inf}{f(n) / g(n)} tends to zero.第一个函数比第二个慢,因为极限lim_{n -> +inf}{f(n) / g(n)}趋于零。

Therefore, asymptotically (ie when you "move" towards the infinite), the first function does not really influence the behavior of the total function, which will strictly depend on the behavior of n*log(n) .因此,渐近地(即,当您向无限“移动”时),第一个函数不会真正影响整个函数的行为,这将严格取决于n*log(n)的行为。 Thus, we say the cost is O(n*log(n)) .因此,我们说成本是O(n*log(n))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM