Sort Colors

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 01, and 2 to represent the color red, white, and blue, respectively.

Example 1:

Input: nums = {2,0,2,1,1,0}
Output: nums= {0,0,1,1,2,2}

Approach

Java


import java.util.Arrays;

public class SortColors {
    public static void main(String[] args) {
        int nums[] = { 202110 };
        sortColors(nums);
        System.out.println(Arrays.toString(nums));
    }

    static void sortColors(int[] nums) {
        int cnt0 = 0, cnt1 = 0, cnt2 = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0)
                cnt0++;
            else if (nums[i] == 1)
                cnt1++;
            else
                cnt2++;
        }
        int i = 0;
        while (cnt0 > 0) {
            nums[i++] = 0;
            cnt0--;
        }
        while (cnt1 > 0) {
            nums[i++] = 1;
            cnt1--;
        }
        while (cnt2 > 0) {
            nums[i++] = 2;
            cnt2--;
        }
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

void sortColors(vector<int>& nums
{
        int cnt0=0,cnt1=0,cnt2=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]==0)
                   cnt0++;
            else if(nums[i]==1)
                   cnt1++;
            else
                  cnt2++;
        }
        int i=0;
      while(cnt0)
      {
          nums[i++]=0;
          cnt0--;
      }
    while(cnt1)
    {
        nums[i++]=1;
        cnt1--;
    }
        while(cnt2)
        {
            nums[i++]=2;
            cnt2--;
        }
}
int main()
{
    vector<intnums ={2,0,2,1,1,0};
    sortColors(nums);
    for(int i=0;i<nums.size();i++)
       cout<<nums[i]<<" ";
     return 0;
}


No comments:

Post a Comment