75. Sort Colors #51
-
Given an array We will use the integers You must solve this problem without using the library's sort function. Example 1:
Example 2:
Constraints:
Follow-up: Could you come up with a one-pass algorithm using only constant extra space? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
To solve this problem, we can follow these steps: The goal is to sort the array Approach:The most efficient way to solve this problem is by using the Dutch National Flag algorithm, which is a one-pass algorithm with constant extra space. The idea is to use three pointers:
Algorithm:
This algorithm sorts the array in-place with a single pass. Let's implement this solution in PHP: 75. Sort Colors <?php
function sortColors(&$nums) {
$low = 0;
$mid = 0;
$high = count($nums) - 1;
while ($mid <= $high) {
if ($nums[$mid] == 0) {
// Swap nums[low] and nums[mid]
$temp = $nums[$low];
$nums[$low] = $nums[$mid];
$nums[$mid] = $temp;
$low++;
$mid++;
} elseif ($nums[$mid] == 1) {
$mid++;
} else { // nums[$mid] == 2
// Swap nums[mid] and nums[high]
$temp = $nums[$high];
$nums[$high] = $nums[$mid];
$nums[$mid] = $temp;
$high--;
}
}
}
// Example usage:
$nums1 = [2, 0, 2, 1, 1, 0];
sortColors($nums1);
print_r($nums1); // Output: [0, 0, 1, 1, 2, 2]
$nums2 = [2,0,1];
sortColors($nums2);
print_r($nums2); // Output: [0,1,2]
?> Explanation:
This approach is optimal with O(n) time complexity and O(1) space complexity. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
The goal is to sort the array
nums
with elements representing the colors red (0), white (1), and blue (2) in one pass, using constant extra space.Approach:
The most efficient way to solve this problem is by using the Dutch National Flag algorithm, which is a one-pass algorithm with constant extra space. The idea is to use three pointers:
low
to track the position for the next 0 (red),mid
to traverse the array,high
to track the position for the next 2 (blue).Algorithm:
Initialize three pointers:
low
at the start (0),mid
at the start (0),high
at the end (n-1) of the array.Traverse the array with
mid
:nums[mid]
is0
(red), …