IN JAVA PLEASE
This problem requires you to code the Merge part of the Merge Sort algorithm. The Merge step merges n elements which takes O(n) time. Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Any code that is found to exceed linear time will fail the tests.
Example 1:
Input:
nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3
Output:
[1,2,2,3,5,6]
public class MergeSortedArrays1 { public static int[] merge(int nums1[], int m, int nums2[], int n){ int i = 0,j = 0,k = 0; int arr[] = new int[m+n]; while(i<m && j<n){ if(nums1[i] <= nums2[j]){ arr[k++] = nums1[i++]; } else { arr[k++] = nums2[j++]; } } while (i<m){ arr[k++] = nums1[i++]; } while (j<n){ arr[k++] = nums2[j++]; } return arr; } public static void main(String args[]){ int nums1[] = {1,2,3,0,0,0}; int m = 3; int nums2[] = {2,5,6}; int n = 3; int res[] = merge(nums1,m,nums2,n); for(int i = 0;i<res.length;i++){ System.out.print(res[i]+" "); } } }
1 2 2 3 5 6
Get Answers For Free
Most questions answered within 1 hours.