Description of the problem: assume that nums1 have enough space (size is greater or equal to m + n) to Hol D additional elements from Nums2. The number of elements initialized in nums1 and nums2 is m and n respectively.
Algorithm Analysis: Merge two arrays, but the merged array is the original array 1, cannot create new space, assuming that the array 1 has enough space, from backward to forward, to avoid overwriting problems. Similar problems include the merging of two ordered lists, linked lists and arrays.
From backward to forward comparison, you will not encounter problems with overrides public class Mergesortedarray{public void merge (int[] nums1, int m, int[] nums2, int n) {int i = m-1, j = N-1;int z = m+n-1; while (i >= 0 && J >= 0) { if (Nums1[i] > Nums2[j]) { nums1[z--] = nums1[i--]; } else { nums1[z--] = nums2[j--]; } } if (I < 0) {for (int k = j; k >= 0; k--) { nums1[z--] = nums2[k] ; }}}
Merge two ordered linked lists:
public class Solution {public ListNode mergetwolists (listnode L1, ListNode L2) { ListNode dumy = new ListNode (0); ListNode head = dumy; while (L1 = null && L2! = null) { if (L1.val < L2.val) { dumy.next = L1; L1 = L1.next; } else { dumy.next = L2; L2 = L2.next; } Dumy = Dumy.next; } if (L1 = = null) { dumy.next = L2; } if (L2 = = null) { dumy.next = L1; } return head.next;} }
Mergesortedarray, merging two ordered arrays