【问题标题】:What is the time complexity of this segment tree algorithm?这个分段树算法的时间复杂度是多少?
【发布时间】:2020-09-04 00:33:20
【问题描述】:
class SegTreeNode {
public:
  int start;
  int end;
  int min;
  SegTreeNode *left;
  SegTreeNode *right;
  SegTreeNode(int start, int end) {
    this->start = start;
    this->end = end;
    left = right = NULL;
  }
};

class Solution {
public:
  int largestRectangleArea(vector<int>& heights) {
    if (heights.size() == 0) return 0;
    // first build a segment tree
    SegTreeNode *root = buildSegmentTree(heights, 0, heights.size() - 1);
    // next calculate the maximum area recursively
    return calculateMax(heights, root, 0, heights.size() - 1);
  }
  
  int calculateMax(vector<int>& heights, SegTreeNode* root, int start, int end) {
    if (start > end) {
      return -1;
    }
    if (start == end) {
      return heights[start];
    }
    int minIndex = query(root, heights, start, end);
    int leftMax = calculateMax(heights, root, start, minIndex - 1);
    int rightMax = calculateMax(heights, root, minIndex + 1, end);
    int minMax = heights[minIndex] * (end - start + 1);
    return max( max(leftMax, rightMax), minMax );
  }
  
  SegTreeNode *buildSegmentTree(vector<int>& heights, int start, int end) {
    if (start > end) return NULL;
    SegTreeNode *root = new SegTreeNode(start, end);
    if (start == end) {
        root->min = start;
      return root;
    } else {
      int middle = (start + end) / 2;
      root->left = buildSegmentTree(heights, start, middle);
      root->right = buildSegmentTree(heights, middle + 1, end);
      root->min = heights[root->left->min] < heights[root->right->min] ? root->left->min : root->right->min;
      return root;
    }
  }
  
  int query(SegTreeNode *root, vector<int>& heights, int start, int end) {
    if (root == NULL || end < root->start || start > root->end) return -1;
    if (start <= root->start && end >= root->end) {
      return root->min;
    }
    int leftMin = query(root->left, heights, start, end);
    int rightMin = query(root->right, heights, start, end);
    if (leftMin == -1) return rightMin;
    if (rightMin == -1) return leftMin;
    return heights[leftMin] < heights[rightMin] ? leftMin : rightMin;
  }
};

这是解决这个leet代码问题https://leetcode.com/problems/largest-rectangle-in-histogram/

我相信下面的代码应该有 logN * logN 的平均时间复杂度和 NlogN 的最坏情况时间复杂度

我的理由是,calculateMax 的递归平均需要 logN,并且只会在数组中矩形的高度按升序或降序排序的最坏情况下恶化到 N。

我只是想知道我的逻辑是否正确,并希望得到某种类型的确认。

谢谢:)

【问题讨论】:

标签: c++ performance recursion data-structures time-complexity


【解决方案1】:

你的推理是正确的。但是你为什么使用 Segment tree 让代码变得如此复杂。也可以使用堆栈来完成。

请参考:maximize-the-rectangular-area-under-histogram

【讨论】:

    猜你喜欢
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多