What is the time complexity of this function?

2019-07-12 02:23发布

Here's a sample solution for Sliding Window Maximum problem in Java.

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

I want to get the time and space complexity of this function. Here's what I think would be the answer:

Time: O((n-k)(k * logk)) == O(nklogk)

Space (auxiliary): O(n) for return int[] and O(k) for pq. Total of O(n).

Is this correct?

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;
}

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-12 02:42

You're right in most of the part except -

for (int j = i; j < i + k; j++) {
     // time k*logk (the part I'm not sure about)
     pq.offer(a[j]);
}

Here total number of executions is log1 + log2 + log3 + log4 + ... + logk. The summation of this series -

log1 + log2 + log3 + log4 + ... + logk = log(k!)

And second thought is, you can do it better than your linearithmic time solution using double-ended queue property which will be O(n). Here is my solution -

public int[] maxSlidingWindow(int[] nums, int k) {      
    if (nums == null || k <= 0) {
        return new int[0];
    }
    int n = nums.length;
    int[] result = new int[n - k + 1];
    int indx = 0;

    Deque<Integer> q = new ArrayDeque<>();

    for (int i = 0; i < n; i++) {

        // remove numbers out of range k
        while (!q.isEmpty() && q.peek() < i - k + 1) {
            q.poll();
        }

        // remove smaller numbers in k range as they are useless
        while (!q.isEmpty() && nums[q.peekLast()] < nums[i]) {
            q.pollLast();
        }

        q.offer(i);
        if (i >= k - 1) {
            result[indx++] = nums[q.peek()];
        }
    }

    return result;
}

HTH.

查看更多
登录 后发表回答