← switch

26. Remove Duplicates from Sorted Array

easy

Array · Two Pointers

read the problem on leetcode →

first solved 31 Aug 2023 · 3 accepted submissions

python
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        k=1
        for i in range(1, len(nums)):
            if nums[i]!=nums[k-1]:
                nums[k]=nums[i]
                k+=1
        return k

python
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        uni=0
        for i in range(len(nums)):
            if i==0 or nums[i]!=nums[i-1]:
                nums[uni]=nums[i]
                uni+=1
            else:
                pass
        return uni
                    
python
class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        k=0
        past=None
        for i in nums:
            if past==None:
                nums[0]=i
                k+=1
                past=nums[0]

            if past!=i:
                nums[k]=i
                past=i
                k+=1
            else:
                pass
        return k