[LeetCode] 915. Partition Array into Disjoint Intervals
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 inright
. left
andright
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.
分割数组。
给定一个数组 nums ,将其划分为两个连续子数组 left 和 right, 使得:
left 中的每个元素都小于或等于 right 中的每个元素。
left 和 right 都是非空的。
left 的长度要尽可能小。
在完成这样的分组后返回 left 的 长度 。用例可以保证存在这样的划分方法。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/partition-array-into-disjoint-intervals
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题意不难理解,我直接讲思路,需要扫描两遍数组,一遍从右往左,一遍从左往右。我参考了这个帖子。
因为需要比较左半边数组的最大值和右半边数组的最小值,这里我先创建一个和 input 数组等长的数组来记录从右往左扫描的每个不同子数组中的最小值是多少,记为 suffixMin。这样当我遍历到任何一个 index 的位置上的时候,我可以立马知道当前位置的右半边数组的最小值是多少。
第二遍从左往右扫描,用一个 max 变量记录左半边数组的最大值。因为需要让这个分割的位置尽量靠左,所以当我们找到第一个位置满足左半边的最大值 max <= 右半边的最小值的时候,我们就可以返回了。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int partitionDisjoint(int[] nums) { 3 int len = nums.length; 4 int[] suffixMin = new int[len]; 5 suffixMin[len - 1] = nums[len - 1]; 6 for (int i = len - 2; i >= 0; i--) { 7 suffixMin[i] = Math.min(suffixMin[i + 1], nums[i]); 8 } 9 10 int max = 0; 11 for (int i = 0; i < len - 1; i++) { 12 max = Math.max(max, nums[i]); 13 if (max <= suffixMin[i + 1]) { 14 return i + 1; 15 } 16 } 17 return -1; 18 } 19 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
2020-10-24 [LeetCode] 456. 132 Pattern