力扣打卡第二天 分割数组

给定一个数组 nums ,将其划分为两个连续子数组 left 和 right, 使得:

  • left 中的每个元素都小于或等于 right 中的每个元素。
  • left 和 right 都是非空的。
  • left 的长度要尽可能小。
  • 在完成这样的分组后返回 left 的 长度 。

用例可以保证存在这样的划分方法。

class Solution { public:
int partitionDisjoint(vector& nums) {
int n = nums.size();
int LeftMax = nums[0], curMax = nums[0];
// 分界点
int pos = 0;
for (int i = 1; i < n; i++) {
curMax = max(curMax, nums[i]);
// 如果当前元素小于左边数组的最大值时,将分界点的位置更新为当前元素的位置。
if (nums[i] < LeftMax) {
pos = i;
// 注意最边数组的最大值也要随之更新
LeftMax = curMax;
}
}
return pos + 1;
} };

猜你喜欢

转载自blog.csdn.net/qq_46157589/article/details/127499020