2
下面是Java中Sliding Window Maximum问题的示例解决方案。这个函数的时间复杂度是多少?
给定一个数组nums,有一个大小为k的滑动窗口,它从数组的最左边移动到最右边。您只能在窗口中看到 的k个数字。滑动窗口每次移动 向右移动一个位置。
我想获得这个功能的时间和空间的复杂性。这是我觉得这是答案:
时间:O((n-k)(k * logk))
== O(nklogk)
空间(辅助):O(n)
退货int[]
和O(k)
为pq
。共有O(n)
。
这是正确的吗?
private static int[] maxSlidingWindow(int[] a, int k) {
if(a == null || a.length == 0) return new int[] {};
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
// max heap
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
int[] result = new int[a.length - k + 1];
int count = 0;
// time: n - k times
for (int i = 0; i < a.length - k + 1; i++) {
for (int j = i; j < i + k; j++) {
// time k*logk (the part I'm not sure about)
pq.offer(a[j]);
}
// logk
result[count] = pq.poll();
count = count + 1;
pq.clear();
}
return result;
}
'k'确实是一个常数? – Boggartfly
如果k不是常数,那么如何从等式'O((n-k)(k * logk))'中消除? – Boggartfly