Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. Subscribe to see which companies asked this question
publicclass{ publicvoidmerge(int[] nums1, int m, int[] nums2, int n){ if (n == 0) return; if (m == 0) { for (int i = 0; i < n; i++) { nums1[i] = nums2[i]; }
return; } int[] nums3 = newint[m + n];
int a = 0; int b = 0; for (int i = 0; i < n + m; i++) {
if (nums1[a] < nums2[b]) { if (a <= m - 1) { nums3[i] = nums1[a]; a++; }
if (a > m - 1) { while (b < n) { nums3[++i] = nums2[b]; b++;
} break; } } else { if (b <= n - 1) { nums3[i] = nums2[b]; b++; }
if (b > n - 1) { while (a < m) { nums3[++i] = nums1[a]; a++;
} break; } }
} for (int i = 0; i < m + n; i++) { nums1[i] = nums3[i]; } } }
近期评论