Posts leetcode-01
Post
Cancel

leetcode-01

p239

给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 返回 滑动窗口中的最大值 。

1
2
3
4
5
6
7
8
9
10
11
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置                最大值
---------------               -----
[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

单调队列,滑动窗口来写。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//单调队列
class aloneQue{
private:
    deque<int> deque;
public:
    int pop(){
        int temp = deque.front();
        deque.pop_front();
        return temp;
    }
    void push(int x){
        while (deque.size() > 0 && deque.back() < x){
            deque.pop_back();
        }
        deque.push_back(x);
    }
    int top(){
        return deque.front();
    }
};


class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        aloneQue aloneQue;
        int i;
        for ( i = 0; i < k-1; ++i) {
            aloneQue.push(nums[i]);
        }
//        --i;
        vector<int> res;
        int temp;
        while (i < nums.size()){
            aloneQue.push(nums[i]);
            res.push_back(aloneQue.top());
            if (aloneQue.top() == nums[i+1-k])
                aloneQue.pop();
            ++i;
        }
        return res;
    }
};

p010 对称二叉树

给你一个二叉树的根节点 root , 检查它是否轴对称。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
    bool compare(TreeNode *left,TreeNode *right){
        if (left == nullptr && right == nullptr) return true;
        else if (left == nullptr || right == nullptr) return false;
        else if (left->val != right->val) return false;

        bool b1 = compare(left->left,right->right);
        bool b2 = compare(left->right,right->left);
        bool res = b1*b2;
        return res;
    }

    bool isSymmetric(TreeNode* root) {
        if (!root) return true;
        return compare(root->left,root->right);
    }
};
This post is licensed under CC BY 4.0 by the author.

Contents

Trending Tags