Thursday, February 25, 2021

Remove Duplicates from Sorted Array

Problem: Given a sorted array, remove the duplicates in-place such that each element appears only once and returns the new length.

Example:

Input: nums = [1,1,2,2,2,3,3,3,3,4]
Output: 4, nums = [1,2,3,4,...]
Explanation: Your function should return length = 4, with the first four elements of nums being modified to 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.


Approach: Nothing to explain here. Ju    st look at the implementation to understand the approach as it is fairly easy.


Implementation in C#:

    public int RemoveDuplicates(int[] nums) 

    {

        if (nums?.Length == 0)

        {

            return 0;

        }    

        int j = 1;

        for (int i = 1; i < nums.Length; ++i)

        {

            if (nums[i] != nums[i - 1])

            {

                nums[j++] = nums[i];

            }

        }

        return j;

    }


Complexity: O(n)

No comments:

Post a Comment