返回介绍

solution / 0900-0999 / 0915.Partition Array into Disjoint Intervals / README_EN

发布于 2024-06-17 01:03:33 字数 3312 浏览 0 评论 0 收藏 0

915. Partition Array into Disjoint Intervals

中文文档

Description

Given an integer array nums, partition it into two (contiguous) subarrays left and right so that:

  • Every element in left is less than or equal to every element in right.
  • left and right are non-empty.
  • left has the smallest possible size.

Return _the length of _left_ after such a partitioning_.

Test cases are generated such that partitioning exists.

 

Example 1:

Input: nums = [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]

Example 2:

Input: nums = [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]

 

Constraints:

  • 2 <= nums.length <= 105
  • 0 <= nums[i] <= 106
  • There is at least one valid answer for the given input.

Solutions

Solution 1

class Solution:
  def partitionDisjoint(self, nums: List[int]) -> int:
    n = len(nums)
    mi = [inf] * (n + 1)
    for i in range(n - 1, -1, -1):
      mi[i] = min(nums[i], mi[i + 1])
    mx = 0
    for i, v in enumerate(nums, 1):
      mx = max(mx, v)
      if mx <= mi[i]:
        return i
class Solution {
  public int partitionDisjoint(int[] nums) {
    int n = nums.length;
    int[] mi = new int[n + 1];
    mi[n] = nums[n - 1];
    for (int i = n - 1; i >= 0; --i) {
      mi[i] = Math.min(nums[i], mi[i + 1]);
    }
    int mx = 0;
    for (int i = 1; i <= n; ++i) {
      int v = nums[i - 1];
      mx = Math.max(mx, v);
      if (mx <= mi[i]) {
        return i;
      }
    }
    return 0;
  }
}
class Solution {
public:
  int partitionDisjoint(vector<int>& nums) {
    int n = nums.size();
    vector<int> mi(n + 1, INT_MAX);
    for (int i = n - 1; ~i; --i) mi[i] = min(nums[i], mi[i + 1]);
    int mx = 0;
    for (int i = 1; i <= n; ++i) {
      int v = nums[i - 1];
      mx = max(mx, v);
      if (mx <= mi[i]) return i;
    }
    return 0;
  }
};
func partitionDisjoint(nums []int) int {
  n := len(nums)
  mi := make([]int, n+1)
  mi[n] = nums[n-1]
  for i := n - 1; i >= 0; i-- {
    mi[i] = min(nums[i], mi[i+1])
  }
  mx := 0
  for i := 1; i <= n; i++ {
    v := nums[i-1]
    mx = max(mx, v)
    if mx <= mi[i] {
      return i
    }
  }
  return 0
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文