给你一个下标从 0 开始的整数数组 nums
,如果满足下述条件,则认为数组 nums
是一个 美丽数组 :
nums.length
为偶数- 对所有满足
i % 2 == 0
的下标i
,nums[i] != nums[i + 1]
均成立
注意,空数组同样认为是美丽数组。
你可以从 nums
中删除任意数量的元素。当你删除一个元素时,被删除元素右侧的所有元素将会向左移动一个单位以填补空缺,而左侧的元素将会保持 不变 。
返回使 nums
变为美丽数组所需删除的 最少 元素数目。
示例 1:
输入:nums = [1,1,2,3,5] 输出:1 解释:可以删除 nums[0] 或 nums[1],这样得到的 nums = [1,2,3,5] 是一个美丽数组。可以证明,要想使 nums 变为美丽数组,至少需要删除 1 个元素。
示例 2:
输入:nums = [1,1,2,2,3,3] 输出:2 解释:可以删除 nums[0] 和 nums[5],这样得到的 nums = [1,2,2,3] 是一个美丽数组。可以证明,要想使 nums 变为美丽数组,至少需要删除 2 个元素。
提示:
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^5
提示 1
Delete as many adjacent equal elements as necessary.
提示 2
If the length of nums is odd after the entire process, delete the last element.
解法1:栈
Java版:
class Solution {
public int minDeletion(int[] nums) {
Deque<Integer> stack = new LinkedList<>();
int idx = 0;
for (int num: nums) {
if (idx % 2 == 1 && stack.peek() == num) {
continue;
} else {
stack.push(num);
idx++;
}
}
return stack.size() % 2 == 0 ? nums.length - stack.size() : nums.length - stack.size() + 1;
}
}
Python3版:
class Solution:
def minDeletion(self, nums: List[int]) -> int:
stack = []
idx = 0
for num in nums:
if idx % 2 == 1 and stack[-1] == num:
continue
else:
stack.append(num)
idx += 1
return len(nums) - len(stack) if len(stack) % 2 == 0 else len(nums) - len(stack) + 1
复杂度分析
-
时间复杂度:O(n),其中 n 是数组 nums 的长度。
-
空间复杂度:O(n)。