What is the point of sorting? My workaround in C#


  • 0
    L

    I do not quite get what the problem is about: There is no real collection of objects but just an array of integers whose elements are limited to 0, 1 and 2. Therefore why you need to pretend any sorting is required?

    public void SortColors(int[] nums)
    {
      int numberOfOnes = GetNumberofOnes(nums);
      int numberOfTwos = (nums.Sum() - numberOfOnes) / 2;
      int numberOfZeros = nums.Count() - numberOfOnes - numberOfTwos;
    
      for(int i = 0; i < numberOfZeros; i ++)
      {
        nums[i] = 0;
      }
    
      for (int i = numberOfZeros; i < numberOfZeros + numberOfOnes; i++)
      {
        nums[i] = 1;
      }
    
      for (int i = numberOfZeros + numberOfOnes; i < nums.Count(); i++)
      {
        nums[i] = 2;
      }
    }
    
    int GetNumberofOnes(int[] nums)
    {
      int sumOfOnes = 0;
      for (int i = 0; i < nums.Count(); i++)
      {
        sumOfOnes += nums[i] & 1;
      }
    
      return sumOfOnes;
    }

Log in to reply
 

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