Untitled
unknown
plain_text
10 months ago
2.2 kB
11
Indexable
package ARRAYS;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class MergeArrays {
/**
*This class Takes two integer arrays nums1 and nums2.
* Merge both the arrays into a single array sorted in non-decreasing order.
* The final sorted array should be stored inside the array nums1 and it should be done in-place
* nums1 has a length of m + n, where the first m elements denote the elements of nums1 and rest are 0s.
* nums2 has a length of n.
*
* Examples:
* Input: nums1 = [-5, -2, 4, 5], nums2 = [-3, 1, 8]
* Output: [-5, -3, -2, 1, 4, 5, 8]
* Explanation:
* The merged array is: [-5, -3, -2, 1, 4, 5, 8], where [-5, -2, 4, 5] are from nums1 and [-3, 1, 8] are from nums2
*
* Input: nums1 = [0, 2, 7, 8], nums2 = [-7, -3, -1]
* Output: [-7, -3, -1, 0, 2, 7, 8]
* Explanation:
* The merged array is: [-7, -3, -1, 0, 2, 7, 8], where [0, 2, 7, 8] are from nums1 and [-7, -3, -1] are from nums2
*/
public static int [] merge(int [] nums1, int[] nums2,int m,int n) {
List<Integer> merge = new ArrayList<>();
for (int i = 0; i < m; i++) {
merge.add(nums1[i]);
}
for (int i = 0; i < n; i++) {
merge.add (nums2[i]);
}
for (int i = 0; i < (m+n) ; i++) {
nums1[i] = merge.get(i);
}
Arrays.sort(nums1);
return nums1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("ENTER ARR1 SIZE -> ");
int m = sc.nextInt();
System.out.print("ENTER ARR2 SIZE -> ");
int n = sc.nextInt();
System.out.println("ENTER ARR1 -> ");
int nums1[] = new int[m+n];
for (int i = 0; i < m+n; i++) {
nums1[i] = sc.nextInt();
}
System.out.println("ENTER ARR2 -> ");
int nums2[] = new int[n];
for (int i = 0; i < n; i++) {
nums2[i] = sc.nextInt();
}
System.out.println("ARRAY -> " + Arrays.toString(merge(nums1,nums2,m,n)));
}
}
Editor is loading...
Leave a Comment