O(n) Counting-Sort Solution in C#


  • 0
    J
    public class Solution
    {
        public void SortColors(int[] nums)
        {
            int redCount = 0, whiteCount = 0, blueCount = 0;
            foreach (int num in nums)
            {
                switch (num)
                {
                    case 0:
                    {
                        ++redCount;
                        break;
                    }
                    case 1:
                    {
                        ++whiteCount;
                        break;
                    }
                    case 2:
                    {
                        ++blueCount;
                        break;
                    }
                    default:
                    {
                        throw new ArgumentException("Illegally formatted input.");
                    }
                }
            }
            
            int index;
            for (index = 0; index < redCount; ++index)
            {
                nums[index] = 0;
            }
            
            for (; index < redCount + whiteCount; ++index)
            {
                nums[index] = 1;
            }
            
            for (; index < nums.Length; ++index)
            {
                nums[index] = 2;
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.