Home

C# Remove Duplicates From Integer Array

Worth noting this is for sequential arrays that only rise in the number in the array - ie [1,2,3...] and not [1,3,2/...]

public class Solution
{
    //https://leetcode.com/problems/remove-duplicates-from-sorted-array

    public static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("Enter the Array");
            string s = Console.ReadLine();
            s = s.Replace("[", "");
            s = s.Replace("]", "");
            string[] sArray = s.Split(",");
            int[] iArray = new int[sArray.Length];
            for (int i = 0; i < sArray.Length; i++)
            {
                iArray[i] = Convert.ToInt32(sArray[i]);
            }

            int iReturn = RemoveDuplicates(iArray);

            Console.WriteLine(iReturn);
        }
    }

    public static int RemoveDuplicates(int[] nums)
    {
        int itemToMatch = -int.MaxValue;
        int IArrayCount = 0;

        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] != itemToMatch)
            {
                nums[IArrayCount] = nums[i];
                IArrayCount++;
            }

            itemToMatch= nums[i];

        }

        return IArrayCount;
    }
}

 

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog