From a4aec711fed1c90ff9f09c6a3255b8d760f8966a Mon Sep 17 00:00:00 2001 From: aucker Date: Thu, 29 Aug 2024 00:09:16 +0800 Subject: [PATCH] Aug27: Sliding window problem [H] use sliding windows, w/ time: O(NlogN), space: O(N) --- daily/Aug27.cc | 44 ++++++++++++++++++++++++++++++++++++++++++++ format.sh | 4 +++- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 daily/Aug27.cc diff --git a/daily/Aug27.cc b/daily/Aug27.cc new file mode 100644 index 0000000..c6bb536 --- /dev/null +++ b/daily/Aug27.cc @@ -0,0 +1,44 @@ +#include +#include +using namespace std; + +class Solution { + public: + /** + * @brief LC3134: Median of the uniqueness array [H] + * Sliding window. Time: O(NlogN), Space: O(N) + * + * @param nums + * @return int + */ + int medianOfUniquenessArray(vector& nums) { + int len = nums.size(); + long long k = ((long long)len * (len + 1) / 2 + 1) / 2; + + auto check = [&](int upper) { + long long cnt = 0; + int l = 0; + unordered_map freq; + for (int r = 0; r < len; r++) { + freq[nums[r]]++; // expand right + while (freq.size() > upper) { // too many elements in window + int out = nums[l++]; + if (--freq[out] == 0) { // out left + freq.erase(out); + } + } + cnt += r - l + 1; // right is r, r - l + 1 + if (cnt >= k) { + return true; + } + } + return false; + }; + int le = 0, ri = len; + while (le + 1 < ri) { + int mid = (le + ri) / 2; + (check(mid) ? ri : le) = mid; + } + return ri; + } +}; diff --git a/format.sh b/format.sh index acb1600..7eadcdc 100755 --- a/format.sh +++ b/format.sh @@ -2,6 +2,8 @@ PROJECT_DIR="./daily" -find $PROJECT_DIR -name uthash -prune -o -name "*.cpp" -o -name "*.c" -o -name "*.h" | xargs clang-format -i +# find $PROJECT_DIR -name uthash -prune -o -name "*.cpp" -o -name "*.c" -o -name "*.h" | xargs clang-format -i + +find $PROJECT_DIR -name uthash -prune -o \( -name "*.cpp" -o -name "*.c" -o -name "*.h" \) -print0 | xargs -0 clang-format -i git add --all