703364. Merging two unsorted arrays in sorted order
Easy
Merging two unsorted arrays in sorted order
Summary
This problem involves merging two unsorted arrays into a single, sorted array. The key concepts involved are sorting and data structures, as indicated by the tags "Sorting" and "Arrays".
Detailed Explanation
The approach to solving this problem is to first concatenate both arrays into one, and then sort it using a suitable algorithm such as QuickSort or MergeSort.
Here's a step-by-step breakdown of the solution:
- Concatenate the two input arrays
arr1andarr2into a single arrayresult. - Sort the
resultarray using a sorting algorithm like QuickSort or MergeSort. - Return the sorted
resultarray as the final output.
Here's an example of how this process would work with two input arrays [4, 7] and [3, 9, 10]. First, we concatenate them into one array: [4, 7, 3, 9, 10]. Then, we sort it to get the final output: [3, 4, 7, 9, 10].
The time complexity of this solution is O(n log n) due to the sorting step. The space complexity is O(n) for storing the concatenated array.
Optimized Solutions
Java
public int[] mergeSortedArrays(int[] arr1, int[] arr2) {
int[] result = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, result, 0, arr1.length);
System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
Arrays.sort(result);
return result;
}