diff --git a/daily/June6.cpp b/daily/June6.cpp index 6c56b9d..0b6eb5b 100644 --- a/daily/June6.cpp +++ b/daily/June6.cpp @@ -22,4 +22,45 @@ class Solution { } return ans; } + + /** + * Sorted Merge LCCI [E] + * 1. from back to begin + * Time: O(n), Space: O(1) + */ + void merge(vector& A, int m, vector& B, int n) { + int k = m + n - 1; + int i = m - 1, j = n - 1; + while (k >= 0 && (i >= 0 || j >= 0)) { + if (i >= 0 && j >= 0 && A[i] >= B[j]) { + A[k] = A[i]; + i--; + k--; + } else if (i >= 0 && j >= 0 && A[i] < B[j]) { + A[k] = B[j]; + j--; + k--; + } else if (i >= 0 && j < 0) { + A[k] = A[i]; + i--; + k--; + } else if (i < 0 && j >= 0) { + A[k] = A[j]; + j--; + k--; + } + } + } + + /** + * Use STD library of std::sort + * Time: Average: O(nlogn) + * Both works, but this is easy to implement, no much edge case + */ + void mergeSTD(vector& A, int m, vector& B, int n) { + for (int i = 0; i < n; i++) { + A[m + i] = B[i]; + } + sort(A.begin(), A.end()); + } };