[LeetCode] 2369. Check if There is a Valid Partition For The Array

发布时间 2023-08-14 13:13:38作者: CNoodle

You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.

We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:

  1. The subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good.
  2. The subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good.
  3. The subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not.

Return true if the array has at least one valid partition. Otherwise, return false.

Example 1:

Input: nums = [4,4,4,5,6]
Output: true
Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].
This partition is valid, so we return true.

Example 2:

Input: nums = [1,1,1,2]
Output: false
Explanation: There is no valid partition for this array.

Constraints:

  • 2 <= nums.length <= 105
  • 1 <= nums[i] <= 106

检查数组是否存在有效划分。

给你一个下标从 0 开始的整数数组 nums ,你必须将数组划分为一个或多个 连续 子数组。

如果获得的这些子数组中每个都能满足下述条件 之一 ,则可以称其为数组的一种 有效 划分:

  1. 子数组 恰 由 2 个相等元素组成,例如,子数组 [2,2] 。
  2. 子数组 恰 由 3 个相等元素组成,例如,子数组 [4,4,4] 。
  3. 子数组 恰 由 3 个连续递增元素组成,并且相邻元素之间的差值为 1 。例如,子数组 [3,4,5] ,但是子数组 [1,3,5] 不符合要求。

如果数组 至少 存在一种有效划分,返回 true ,否则,返回 false 。

思路是动态规划,有点像爬楼梯那一类的题目。假设 input 数组的长度为 n,那么这里我也创建一个长度为 n + 1 的 dp 数组,dp 数组的定义为走到位置 i 的时候,这个长度为 i 的子数组能否组成一个有效划分。是否可以被有效划分的定义参照如上三点,有三种不同情况,可直接参见代码。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public boolean validPartition(int[] nums) {
 3         var n = nums.length;
 4         var dp = new boolean[n + 1];
 5         dp[0] = true;
 6         for (var i = 1; i < n; ++i)
 7             if (dp[i - 1] && nums[i] == nums[i - 1] ||
 8                 i > 1 && dp[i - 2] && (nums[i] == nums[i - 1] && nums[i] == nums[i - 2] ||
 9                 nums[i] == nums[i - 1] + 1 && nums[i] == nums[i - 2] + 2)) {
10                     dp[i + 1] = true;
11                 }
12         return dp[n];
13     }
14 }

 

LeetCode 题目总结