LeetCode每日一题(2216. Minimum Deletions to Make Array Beautiful)

给定一个整数数组nums,如果数组长度为偶数且相邻元素不相等,则认为数组是美丽的。你可以删除任意数量的元素,删除后所有右侧元素将向左移动填补空缺。返回使nums变得美丽的最小删除数。例如,输入nums = [1,1,2,3,5],删除一个元素后可以变成[1,2,3,5],变得美丽。" 137179295,22711130,Python实现Gauss-Seidel迭代法详解及应用,"['Python', '数值计算', '算法实现']

You are given a 0-indexed integer array nums. The array nums is beautiful if:

nums.length is even.
nums[i] != nums[i + 1] for all i % 2 == 0.
Note that an empty array is considered beautiful.

You can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged.

Return the minimum number of elements to delete from nums to make it beautiful.

Example 1:

Input: nums = [1,1,2,3,5]
Output: 1

Explanation: You can delete either nums[0] or nums[1] to make nums = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make nums beautiful.

Example 2:

Input: nums = [1,1,2,2,3,3]
Output: 2

Explanation: You can delete nums[0] and nums[5] to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 105

假设 i % 2 == 0, 如果 nums[i] != nums[i+1],我们就可以检查下一个 pair, i += 2, 如果 nums[i] == nums[i+1], 此时我们可以删掉 nums[i+1]之前的任意一个数字(包括 nums[n+1])来保持 beautiful, 同时 nums[n+1]之后的数字奇偶位置都发生变化, 所以我们如果再 i += 2 的话就跳到了奇数位上, 所以此时我们需要 i += 1。 遍历完成后我们还需要看一下最终剩下的元素数量, 如果是奇数的话,为了满足题目中的第一个条件, 我们需要再删掉一个数



impl Solution {
    pub fn min_deletion(nums: Vec<i32>) -> i32 {
        let mut i = 0;
        let mut deleted = 0;
        while i + 1 < nums.len() {
            if nums[i] == nums[i + 1] {
                deleted += 1;
                i += 1;
                continue;
            }
            i += 2
        }
        if (nums.len() - deleted as usize) % 2 == 0 {
            deleted
        } else {
            deleted + 1
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值