Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details

describe

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.Copy the code

Note:

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^5

parsing

You are given an integer array with 0 index nums. An array nums is beautiful and an empty array is considered beautiful if the following conditions are met:

  • Nums. length is even.
  • nums[i] ! = nums[I + 1] for all I % 2 == 0.

We can remove any number of elements from numS. When an element is deleted, all elements to the right of the deleted element are moved one unit to the left to fill the created space, while all elements to the left of the deleted element remain unchanged. Returns the minimum number of elements to remove from NUMS to make it a beautiful array.

Nums [I] == nums[I + 1] if nums[I] == nums[I + 1] if nums[I] == nums[I + 1] if nums[I] == nums[I + 1] Index I plus one continues forward through nums; If the nums [I]! = nums[I + 1], then we increment index I by 2 and continue to traverse NUMs. If “I” is less than “N” at the end of the loop, all elements following “I” should be removed.

The time complexity is O(N), and the space complexity is O(1).

answer

class Solution(object):
    def minDeletion(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:return 0
        N = len(nums)
        i = 0
        result = 0
        while i < N-1:
            if nums[i] == nums[i+1]:
                result += 1
                i += 1
            else:
                i += 2
        if i < N:
            result += (N-i)
        return result
Copy the code

The results

114/114 Test cases passed. Status: Accepted Runtime: 1696 MS Memory Usage: 25.5 MBCopy the code

The original link

Leetcode.com/contest/wee…

Your support is my biggest motivation