1122. Relative Sort Array #217
-
Topics: Given two arrays Sort the elements of Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem requires sorting an array Key Points:
Approach:
Plan:
Let's implement this solution in PHP: 1122. Relative Sort Array <?php
/**
* @param Integer[] $arr1
* @param Integer[] $arr2
* @return Integer[]
*/
function relativeSortArray($arr1, $arr2) {
$result = array();
// Traverse through the relative order array
for ($i = 0; $i < count($arr2); $i++) {
// Traverse through the target array
for ($j = 0; $j < count($arr1); $j++) {
// If element in target array matches with
// relative order element
if ($arr1[$j] == $arr2[$i]) {
// Add it to the result array
array_push($result, $arr1[$j]);
// Mark the element in target array as visited
$arr1[$j] = -1;
}
}
}
// Sort the remaining elements in the target array
sort($arr1);
// Add the remaining elements to the result array
for ($i = 0; $i < count($arr1); $i++) {
if ($arr1[$i] != -1) {
array_push($result, $arr1[$i]);
}
}
return $result;
}
// Example usage:
$arr1 = [2,3,1,3,2,4,6,7,9,2,19];
$arr2 = [2,1,4,3,9,6];
echo relativeSortArray($arr1, $arr2); // Output: [2,2,2,1,4,3,3,9,6,7,19]
$arr1 = [28,6,22,8,44,17];
$arr2 = [22,28,8,6];
echo relativeSortArray($arr1, $arr2); // Output: [22,28,8,6,17,44]
?> Explanation:
Example Walkthrough:Example 1:
Example 2:
Time Complexity:
Output for Example:
The solution efficiently sorts |
Beta Was this translation helpful? Give feedback.
The problem requires sorting an array
arr1
such that its elements are rearranged to match the relative order of elements found in another arrayarr2
. Elements fromarr2
should appear in the same order inarr1
, and any remaining elements fromarr1
that are not present inarr2
should be placed at the end in ascending order.Key Points:
arr2
are distinct.arr2
are guaranteed to be present inarr1
.arr1
that is not inarr2
should appear at the end, sorted in ascending order.Approach:
Use a Hashmap: The order of
arr2
is essential. By storing the index of each element inarr2
, we can sortarr1
based on the relative order ofarr2
. We will use the v…