Delete array elements in LeetCode

Questions 26 and 80 are about deleting duplicates in an ordered array.

For such issues, we should consider the following:

  • Since k identical numbers are retained, we can directly retain the first k numbers.
  • For any subsequent number, the prerequisite for retaining it is: compare it with the k-th element before the currently written position, and retain it if they are not the same.

26. Remove duplicates from ordered array

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i=0
        for num in nums:
            if i<1 or nums[i-1]!=num:
                nums[i]=num
                i+=1
        return i

80. Remove duplicates in ordered array II

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i=0
        for num in nums:
            if i<2 or nums[i-2]!=num:
                nums[i]=num
                i+=1
        return i

Question 27 is to delete the specified element in the unordered array

27. Remove elements

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i=0
        for num in nums:
            if num!=val:
                nums[i]=num
                i+=1
        return i

Guess you like

Origin blog.csdn.net/hu_wei123/article/details/131891851
Recommended