Problem:
Given sorted integer arrays A and B, merge B into a as one sorted array.
Note:
You could assume that A have enough space (size that's greater or equal to m + n) to the hold additional Eleme NTS from B. The number of elements initialized in A and B is mand n respectively.
Hide TagsArray of PointersTest instructions: Merge two ordinal groups
Thinking:
(1) First merge and reorder, O (m+n) lo (m+n)
(2) Insert from backward forward, without moving element, O (m+n)
Code
Merge sort
Class Solution {public: void merge (int a[], int m, int. b[], int n) {for (int i=0;i<n;i++) a[m+i]=b[i]; Sort (a,a+m+n); }};
Insert from backward to forward comparison
Class Solution {public: void merge (int a[], int m, int b[], int n) { //Start Typing your C + + solution below
//does not write int main () function int index = m + n-1; int aindex = m-1; int bindex = n-1; while (0 <= aindex && 0 <= bindex) { if (B[bindex] > A[aindex]) { a[index--] = b[bindex- -]; } else { a[index--] = a[aindex--]; } } while (0 <= aindex) { a[index--] = a[aindex--]; } while (0 <= bindex) { a[index--] = b[bindex--];}} ;
Leetcode | | 88. Merge Sorted Array