google面试题目3

Given an array and an integer k , find the maximum for each and every contiguous sub array of size k.

Sample Input :
1 2 3 1 4 5 2 3 6
3 [ value of w ] 
Sample Output :  
3 3 4 5 5 5 6

分析:

A natural way most people would think is to try to maintain the queue size the same as the window's

size. Try to break away from this thought and try to think outside of the box. Removing redundant

elements and storing only elements that need to be considered in the queue is the key to achieve the

efficient O(n) solution below.

#include <queue>

using namespace std;

void Funtion(int* A, int n, int w, int* B)
{
    deque<int> dq;
    for (int i=0; i<w; i++) 
    {   
        while(!dq.empty() && (A[i] > A[dq.back()]))
        {
            dq.pop_back(); 
        }
        dq.push_back(i);
    }       
    for (int i=w; i<n; i++)
    {
        B[i-w] = A[dq.front()];
        while (!dq.empty() && (A[i] > A[dq.back()]))
        {
            dq.pop_back();
        }
        while (!dq.empty() && (dq.front() <= (i-w)))
        {
            dq.pop_front();
        }
        dq.push_back(i);
    }
    B[n-w] = A[dq.front()]; // need to save the max value int the last window 
}
int main ( int argc, char *argv[] )
{
    int A[] = {1, 2, 3, 1, 4, 5, 2, 3, 6};
    int n = sizeof(A) / sizeof(A[0]);
    cout << n << endl;
    int w = 3;
    int n_b = n - 3 + 1;
    int* B = new int[n_b];
    Funtion(A, n, w, B);
    for (int i=0; i<n_b; i++)
        printf("%d  ", B[i]);
    printf("\n");
    return 0;
} 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值