当前位置: 首页>后端>正文

LC 406 Queue Reconstruction by Height的Segment Tree解法 C++

最近开始低频做题,主要是时间太久了都忘了,而且我C++也不熟,写几道题可以熟悉一下C++。工作中hack用的挺多的,C++ 和 python 也在用但没用那么多。
这道题有多种解法。可以用priorityQueue来做,也可以用segmentTree来做, 也可以用binary index tree来做。
我先写个Segment Tree的解法

struct MyTreeNode { 
    int start;
    int end;
    int availableSlots;
    MyTreeNode* left;
    MyTreeNode* right;
    MyTreeNode(int a, int b, int slots): start(a), end(b), availableSlots(slots), left(nullptr), right(nullptr) {}
};

class SegmentTree {
private:
    MyTreeNode* root;
public:
    SegmentTree(int start, int end): root(buildTree(start, end)) {
    }
    void fill(vector<int>& people, vector<vector<int>>& ans) {
        fill(people, ans, root, people[1] + 1);
    }
private:
    MyTreeNode* buildTree(int start, int end) {
        if (start > end) return nullptr;
        if (start == end) {
            MyTreeNode* node = new MyTreeNode(start, end, 1);
            return node;
        }
        int mid = start + (end - start) / 2;

        MyTreeNode* node = new MyTreeNode(start, end, end - start + 1);
        node->left = buildTree(start, mid);
        node->right = buildTree(mid + 1, end);
        return node;
    }
    void fill(vector<int>& people, vector<vector<int>>& ans, MyTreeNode* node, int pos) {
        if (node == nullptr) return;
        node->availableSlots--;
        if (node->start == node->end) {
            ans[node->start] = vector<int> {people[0], people[1]};
            return;
        }
        int leftAvailableSlots = node->left->availableSlots;
        if (leftAvailableSlots >= pos) fill(people, ans, node->left, pos);
        else fill(people, ans, node->right, pos - leftAvailableSlots);
    }
};


class Solution {
public:
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
        sort(begin(people), end(people), [](const auto& x, const auto& y) {
            return x[0] != y[0] x[0] < y[0] : x[1] > y[1];
        });
        SegmentTree tree {0, (int) people.size() - 1};
        vector<vector<int>> ans(people.size(), vector<int>(2,0));
        for(auto& person: people) {
            tree.fill(person, ans);
        }
        return ans;
    }
};

C++的几个知识点

  1. sort(begin(people), end(people),...)这个用法
  2. sort里面 lambda函数
  3. vector<vector<int>> ans(people.size(), vector<int>(2,0)); 初始化
    工作中这么写会不会内存泄漏,在何处删掉那些指针 ?

https://www.xamrdz.com/backend/3ed1939091.html

相关文章: