From 47290caf5f06777540b762fae89bcdfadbeac875 Mon Sep 17 00:00:00 2001 From: aucker Date: Thu, 6 Jun 2024 13:28:21 +0800 Subject: [PATCH] chore: merge sort on An array, IN Place That is: Space complexity is O(1), handy implement is O(n) STD lib is O(nlogn) --- daily/June6.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) 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()); + } };