LeetCode 2216. 美化数组的最少删除数

2216. 美化数组的最少删除数

给你一个下标从 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)。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值