lintcode:Sliding Window Maximum

504 篇文章 0 订阅
66 篇文章 0 订阅

Given an array of n integer with duplicate number, and a moving window(size k), move the window at each iteration from the start of the array, find the maximum number inside the window at each moving. 

Example

For array [1, 2, 7, 7, 8], moving window size k = 3. return [7, 7, 8]

At first the window is at the start of the array like this 

[|1, 2, 7| ,7, 8] , return the maximum 7;

then the window move one step forward.

[1, |2, 7 ,7|, 8], return the maximum 7;

then the window move one step forward again.

[1, 2, |7, 7, 8|], return the maximum 8;

Challenge

o(n) time and O(k) memory



/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param A: Given an integer array with no duplicates.
     * @return: The root of max tree.
     */
    TreeNode* maxTreeInt(vector<int> &A, int left, int right) {
        
        if (left > right)
            return NULL;
        
        int maxIdx = left;
        for (int i=left+1; i<=right; i++)
        {
            if (A[i] > A[maxIdx])
                maxIdx = i;
        }
        
        TreeNode *root = new TreeNode(A[maxIdx]);
        
        root->left = maxTreeInt(A, left, maxIdx-1);
        root->right = maxTreeInt(A, maxIdx+1, right);
        
        return root;
    }
     
    TreeNode* maxTree(vector<int> A) {
        // write your code here
        if (A.size() == 0)
            return NULL;
        
        return maxTreeInt(A, 0, A.size()-1);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值