Remove Duplicates from Sorted Array

By   Tewodros   Date Posted: Oct. 13, 2023  Hits: 424   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given an integer array nums sorted in ascending order, remove the duplicates in place with out creating another array. The order of the elements should be kept the same. Then return the number of unique elements in nums.

Example: 

nums = [1,4,4,4,5,5,6,6,7,7,8,8,8,8]

Ans

nums = [1,4,5,6,7,8,…]

count = 6

 

   public int RemoveDuplicates(int[] nums) {

        int count = 1;

        int j = 0;

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

        {

            if(nums[i] != nums[j])

            {            

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

                count++;            

            }  

       }

        return count;

    }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* qgwmnn

Back to Top