Array — Two Pointers (I)

LeetCode(26) — Remove Duplicates From Sorted Arrayhttps://leetcode.com/problems/remove-duplicates-from-sorted-array/

Codes:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        """
        Two pointers:
        Walk through the array and paste the needed elements into specific slots.
        i => the current compared element and next replaced one is i + 1
        j => walk through each element, nums[i+1]=nums[j] if nums[i]==nums[j].
        """
        i, j = 0, 1
        for j in range(1, len(nums)):
            if nums[j] != nums[i]:
                nums[i + 1] = nums[j]
                i += 1
        return i+1
        

Leave a Reply

Your email address will not be published. Required fields are marked *