-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
1122. Relative Sort Array #218
1122. Relative Sort Array #218
Comments
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 |
…285200200 Co-authored-by: kovatz <[email protected]> Co-authored-by: topugit <[email protected]> Co-authored-by: basharul-siddike <[email protected]> Co-authored-by: hafijul233 <[email protected]>
…285200200 Co-authored-by: kovatz <[email protected]> Co-authored-by: topugit <[email protected]> Co-authored-by: basharul-siddike <[email protected]> Co-authored-by: hafijul233 <[email protected]>
Discussed in #217
Originally posted by mah-shamim August 2, 2024
Topics:
Array
,Hash Table
,Sorting
,Counting Sort
Given two arrays
arr1
andarr2
, the elements ofarr2
are distinct, and all elements inarr2
are also inarr1
.Sort the elements of
arr1
such that the relative ordering of items inarr1
are the same as inarr2
. Elements that do not appear inarr2
should be placed at the end ofarr1
in ascending order.Example 1:
Example 2:
Constraints:
1 <= arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
arr2
are distinct.arr2[i]
is inarr1
.The text was updated successfully, but these errors were encountered: