LeetCode Solutions: Remove Duplicates from Sorted Array (With a Twist)

Problem statement: Remove Duplicates from Sorted Array

The twist is to change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially.

Intuition

We tackle this problem with an approach with 2 pointers: 'i' and 'j'(they also point to indices in the 'nums' array). The idea is to sweep through the array and place unique elements at their correct positions.

  1. We compare each element with its predecessor to identify duplicates.
  2. Inside the loop:If the current element (nums[i]) differs from the previous one (nums[i - 1]), it signals a new unique element. We then update nums[j] with this unique value from nums[i], advancing 'j' to mark the next position for another unique element. By doing so, we effectively put distinct elements in the first 'j' indices.
  3. Once the loop completes, the value of 'j' indicates the number of unique elements in the array.

Code

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        unique_count = 0  # Counter for unique numbers
        n = len(nums)
        
        # Loop through the array
        for i in range(n):
            # If the current number is different from the previous unique number
            if i == 0 or nums[i] != nums[unique_count - 1]:
                # Update the next position with the unique number
                nums[unique_count] = nums[i]
                # Increment the count of unique numbers
                unique_count += 1

        # The nums array should have unique_count unique values in the first unique_count positions
        return unique_count        


要查看或添加评论,请登录

Rukshar A.的更多文章

社区洞察

其他会员也浏览了