Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MergeTwoSortedArrays {
- /**
- * Merges two sorted integer arrays into one sorted integer array.
- *
- * <p>This method merges two sorted arrays, nums1 and nums2, and stores the result
- * in nums1. The first m elements of nums1 and the first n elements of nums2 are considered
- * for merging. After the operation, nums1 will contain the merged sorted array.</p>
- *
- * <p>Time Complexity: O(M + N), where M is the size of nums1 and N is the size of nums2.</p>
- * <p>Space Complexity: O(M + N), due to the use of an auxiliary array.</p>
- *
- * @param nums1 The first sorted array. Should have enough space to hold the merged result.
- * @param m The number of meaningful elements in nums1.
- * @param nums2 The second sorted array.
- * @param n The number of meaningful elements in nums2.
- */
- private static void merge(int[] nums1, int m, int[] nums2, int n) {
- int[] a = new int[m + n];
- int i = 0, j = 0, k = 0;
- while (i < m && j < n) {
- if (nums1[i] < nums2[j]) {
- a[k++] = nums1[i++];
- } else if (nums2[j] < nums1[i]) {
- a[k++] = nums2[j++];
- } else {
- a[k++] = nums1[i++];
- a[k++] = nums2[j++];
- }
- }
- if (i < m) {
- while (i < m) {
- a[k++] = nums1[i++];
- }
- }
- if (j < n) {
- while (j < n) {
- a[k++] = nums2[j++];
- }
- }
- for (i = 0; i < m + n; i++) {
- nums1[i] = a[i];
- }
- }
- public static void main(String[] args) {
- int[] nums1 = {1, 2, 3, 0, 0, 0};
- int[] nums2 = {2, 5, 6};
- int m = 3, n = 3;
- merge(nums1, m, nums2, n);
- for (int num : nums1) {
- System.out.print(num + " ");
- }
- System.out.println();
- int[] nums12 = {1};
- int m12 = 1;
- int[] nums22 = {};
- int n22 = 0;
- merge(nums12, m12, nums22, n22);
- for (int num : nums12) {
- System.out.print(num + " ");
- }
- System.out.println();
- int[] nums13 = {0};
- int m13 = 0;
- int[] nums23 = {1};
- int n23 = 1;
- merge(nums13, m13, nums23, n23);
- for (int num : nums13) {
- System.out.print(num + " ");
- }
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement