lintcode:Sliding Window Maximum

来源:互联网 发布:关东大地震 知乎 编辑:程序博客网 时间:2024/05/18 00:32

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
原创粉丝点击