Tuesday, September 8, 2020

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Approach: Maintain count.

        public int RemoveDuplicates(int[] nums)

        {

            if (nums == null)

            {

                return 0;

            }

            if (nums.Length <= 2)

            {

                return nums.Length;

            }

            int j = 1, count = 1; ;

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

            {

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

                {

                    ++count;

                }

                else

                {

                    count = 1;

                }

                if (count <= 2)

                {

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

                }

            }

            return j;

        }

No comments:

Post a Comment