Skip to content

Commit

Permalink
Aug27: Sliding window problem [H]
Browse files Browse the repository at this point in the history
use sliding windows, w/ time: O(NlogN), space: O(N)
  • Loading branch information
aucker committed Aug 28, 2024
1 parent 455ec72 commit a4aec71
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
44 changes: 44 additions & 0 deletions daily/Aug27.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include <unordered_map>
#include <vector>
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<int>& 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<int, int> 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;
}
};
4 changes: 3 additions & 1 deletion format.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit a4aec71

Please sign in to comment.