[leetcode 239]Sliding Window Maximum(c)

问题描述:
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.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position Max
————— —–
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Therefore, return the max sliding window as [3,3,5,5,6,7].

问题分析:保存一个滑动窗口base,先计算前k个数组的最大值。然后滑动窗口,当新入一个值时,当大于当前最大值,更新,并记录maxIndex,当小于最大值时,此时若maxIndex>base,就是此时的最大值。当小于base时,重新计算从base开始的窗口大小值。最坏时间复杂度为O(nk)
代码如下:44ms

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize) {

    int base = 0;
    int baseEnd = numsSize-k+1;
    int *res = (int *)malloc(sizeof(int)*baseEnd);
    if(numsSize==0){
        *returnSize = 0;
        return res;
    }
    int resIndex = 0;
    int max = nums[0];
    int maxIndex = 0;

    int index = 0;

    //base = 0
    for(index = 0;indexindex++){
        if(nums[index]>max){
            max = nums[index];
            maxIndex = index;
        }
    }
    res[resIndex++] = max;
    for(base = 1;baseif(nums[base+k-1]>max){
            max = nums[base+k-1];
            maxIndex = base+k-1;
            res[resIndex++] = max;
        }else if(maxIndex>=base){
            res[resIndex++] = max;
        }else{//maxIndexfor(index = base+1;index<=base+k-1;index++){
                if(nums[index]>max){
                    max = nums[index];
                    maxIndex = index;
                }
            }
            res[resIndex++] = max;
        }
    }
    *returnSize = resIndex;
    return res;
}

更新:参见这里写链接内容,作者利用list模拟一个队列。并维护一个栈,维护一个从大到小的栈。这种方法很好的解决了上述代码中可能有的遍历K个元素的问题。因此,其时间复杂度为O(n).

代码如下:648ms

    public int[] maxSlidingWindow(int[] nums, int k) {
        if(nums.length<=0)
            return new int[0];
        int[] res = new int[nums.length-k+1];

        Stack maxStack = new Stack();
        LinkedList stackIndex = new LinkedList();

        for(int i = 0;iwhile(!maxStack.isEmpty()&&maxStack.peek()if(i-stackIndex.getFirst()+1>k){
                stackIndex.removeFirst();
                maxStack.remove(0);
            }
            if(i+1>=k)
                res[i+1-k] = maxStack.get(0);
        }
        return res;
    }

你可能感兴趣的:(leetcode)