微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

这种分段树算法的时间复杂度是多少?

如何解决这种分段树算法的时间复杂度是多少?

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,heights.size() - 1);
    // next calculate the maximum area recursively
    return calculateMax(heights,root,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,minIndex - 1);
    int rightMax = calculateMax(heights,minIndex + 1,end);
    int minMax = heights[minIndex] * (end - start + 1);
    return max( max(leftMax,rightMax),minMax );
  }
  
  SegTreeNode *buildSegmentTree(vector<int>& heights,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,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 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,end);
    int rightMin = query(root->right,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,在最坏的情况下,数组中矩形的高度按升序或降序排序。

我只想知道我的逻辑是否正确,并希望进行某种确认。

谢谢:)

解决方法

您的推理是正确的。但是,为什么使用细分树使代码如此复杂呢?也可以使用堆栈来完成。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。