In this post, we are going to solve the 75. Sort Colors problem of Leetcode. This problem 75. Sort Colors is a Leetcode medium level problem. Let’s see code, 75. Sort Colors – Leetcode Solution.
Problem
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.
Example 1 :
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2 :
Input: nums = [2,0,1]
Output: [0,1,2]
Constraints
n == nums.length
1 <= n <= 300
nums[i]
is either0
,1
, or2
.
Now, let’s see the code of 75. Sort Colors – Leetcode Solution.
Sort Colors – Leetcode Solution
75. Sort Colors – Solution in Java
class Solution { public void swap(int[] nums, int i, int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } public void sortColors(int[] nums) { int i=0,j=0,k=nums.length-1; while(i <= k){ if(nums[i] == 0){ swap(nums,i,j); i++; j++; }else if(nums[i] == 1){ i++; }else if(nums[i] == 2){ swap(nums,i,k); k--; } } } }
75. Sort Colors – Solution in C++
class Solution { public: void sortColors(vector<int>& nums) { int n = nums.size(); int i = 0,j = 0,k = n-1; while(i<=k) { if(nums[i] == 0) { swap(nums[i++],nums[j++]); } else if(nums[i] == 1) { i++; } else if(nums[i] == 2) { swap(nums[i],nums[k]); k--; } } } };
75. Sort Colors – Solution in Python
class Solution(object): def sortColors(self, nums): n=len(nums) zero,one,two=0,0,n-1 while one<=two: if nums[one]==1: one+=1 elif nums[one]==2: nums[one],nums[two]=nums[two],nums[one] two-=1 else: nums[zero],nums[one]=nums[one],nums[zero] zero+=1 one+=1
Note: This problem 75. Sort Colors is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.