LeetCode 0075. Sort Colors Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0075. Sort Colors

Description

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 either 0, 1, or 2.

 

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

Solutions

Solution 1: Three Pointers

We define three pointers i, j, and k. Pointer i is used to point to the rightmost boundary of the elements with a value of 0 in the array, and pointer j is used to point to the leftmost boundary of the elements with a value of 2 in the array. Initially, i=-1, j=n. Pointer k is used to point to the current element being traversed, initially k=0.

When k < j, we perform the following operations:

  • If nums[k] = 0, then swap it with nums[i+1], then increment both i and k by 1;
  • If nums[k] = 2, then swap it with nums[j-1], then decrement j by 1;
  • If nums[k] = 1, then increment k by 1.

After the traversal, the elements in the array are divided into three parts: [0,i], [i+1,j-1] and [j,n-1].

The time complexity is O(n), where n is the length of the array. Only one traversal of the array is needed. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustC#
class Solution: def sortColors(self, nums: List[int]) -> None: i, j, k = -1, len(nums), 0 while k < j: if nums[k] == 0: i += 1 nums[i], nums[k] = nums[k], nums[i] k += 1 elif nums[k] == 2: j -= 1 nums[j], nums[k] = nums[k], nums[j] else: k += 1(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !