Leetcode brushing record-26. Delete duplicates in sorted array

Insert picture description here

Insert picture description here
Brief introduction of the idea:
Considering the sorting of the array, we set two pointers start and cur,
where start points to the last unique number that can be determined,
cur points to the currently investigated number, and
they point to the first two elements at the beginning
. The two elements are not equal,
we point start to cur, and cur points to cur + 1.
If the elements pointed to are equal, we record cur in an array Indexlist,
and then move cur backward and start unchanged.

Finally, after inverting the indexlist, we pop and delete the corresponding repeated numbers from the first element after the inversion, and
finally output the length.


class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        length = len(nums)
        start = 0
        cur = 1
        suma = 1
        indexlist = []
        while cur < length:
            if nums[start] != nums[cur]:
                start = cur
                cur += 1
                suma += 1
            elif nums[start] == nums[cur]:
                indexlist.append(cur)
                cur += 1
        indexlist = indexlist[::-1]
        for pos in indexlist:
            nums.pop(pos)
        return suma
Published 59 original articles · Liked 14 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/weixin_41545780/article/details/105477297