Leetcode Sort Colors Problem Solution

In this Leetcode Sort Colors Problem Solution 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 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

Leetcode Sort Colors Problem Solution


Problem solution in Python.

def sortColors(self, nums: List[int]) -> None:
        count, i = sorted(Counter(nums).items()), 0
 
        for color, value in count:
            start, end = i, i+value
            nums[start: end] = [color]*value
            i = end

Problem solution in Java.

class Solution {
    public void sortColors(int[] nums) {
        
        int r=0,w=0,b=nums.length-1;
        int temp=0;
        while(w!=b+1)
        {
            if(nums[r]==0)
            {    r++; 
                 w++;
            }            
            else if(nums[w]==1)
                w++;
            else if(nums[w]==0)
            {
                temp=nums[r];
                nums[r]=nums[w];
                nums[w]=temp;                
                w++;
                r++;
                
            }
            else if(nums[b]==2)
                b--;
            else if(nums[b]!=2 && nums[w]==2)
            {
                temp=nums[b];
                nums[b]=nums[w];
                nums[w]=temp;
                b--;
            }    
            
        }
        
    }
   
}


Problem solution in C++.

class Solution {
public:
    void sortColors(vector<int>& nums) {
        unordered_map<int, int> storage;
        for(auto &i : nums) storage[i]++;
        
        int j = 0;
        vector<int> colors = {0, 1, 2};
        for(auto i = 0; i<3; i++){
            while(storage[i]--) {
                nums[j]=i; 
                j++;
            }
        }
    }
};


Problem solution in C.

void sortColors(int* nums, int numsSize){
    int i=0,j=0;
    for(i=0;i<numsSize;i++)
    {
        for(j=0;j<numsSize;j++)
        {
            if(nums[j]>nums[i])
            {
                int temp=nums[i];
                nums[i]=nums[j];
                nums[j]=temp;
            }
       }
    
    }
    return nums;
 
}


Post a Comment

0 Comments