[LeetCode] 2216. Minimum Deletions to Make Array Beautiful

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

美化数组的最少删除数。

给你一个下标从 0 开始的整数数组 nums ,如果满足下述条件,则认为数组 nums 是一个 美丽数组 :
nums.length 为偶数
对所有满足 i % 2 == 0 的下标 i ,nums[i] != nums[i + 1] 均成立
注意,空数组同样认为是美丽数组。
你可以从 nums 中删除任意数量的元素。当你删除一个元素时,被删除元素右侧的所有元素将会向左移动一个单位以填补空缺,而左侧的元素将会保持 不变 。
返回使 nums 变为美丽数组所需删除的 最少 元素数目。

思路

我参考了这个帖子
对应题目的要求

  • 对所有满足 i % 2 == 0 的下标 i ,nums[i] != nums[i + 1] 均成立
    这里我需要一个 boolean 变量 even 记录目前遍历到的下标是奇数还是偶数。如果当前的 i 是奇数,可以不处理;如果当前的 i 是偶数且 nums[i] == nums[i + 1],我们一定要删除一个,但是无所谓删除 nums[i] 还是 nums[i + 1],这里我们只要记录删除了一个,即 count++ 就好。因为无论删除哪个,之后的所有元素的下标都往左移动一步,比如 i + 2 变成 i + 1,i + 3 变成 i + 2 等等。
    所以在遍历的过程中我们一直需要去追踪当前的 i 到底是奇数还是偶数以判断当 nums[i] == nums[i + 1] 的时候要不要删除元素。

  • nums.length 为偶数
    满足第一个条件之后我们最后判断数组长度 n - 要删除的元素个数 count 的奇偶性,如果是奇数,则再删除一个元素即可

复杂度

时间O(n)
空间O(1)

代码

Java实现

class Solution {
    public int minDeletion(int[] nums) {
        int n = nums.length;
		boolean even = true;
		int count = 0;
		for (int i = 0; i + 1 < n; i++) {
			if (nums[i] == nums[i + 1] && even) {
				count++;
			} else {
				even = !even;
			}
		}
		if ((n - count) % 2 == 1) {
			count++;
		}
		return count;
    }
}
posted @ 2023-11-22 04:42  CNoodle  阅读(3)  评论(0编辑  收藏  举报