Skip to content

Commit a4aec71

Browse files
committed
Aug27: Sliding window problem [H]
use sliding windows, w/ time: O(NlogN), space: O(N)
1 parent 455ec72 commit a4aec71

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

daily/Aug27.cc

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <unordered_map>
2+
#include <vector>
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
/**
8+
* @brief LC3134: Median of the uniqueness array [H]
9+
* Sliding window. Time: O(NlogN), Space: O(N)
10+
*
11+
* @param nums
12+
* @return int
13+
*/
14+
int medianOfUniquenessArray(vector<int>& nums) {
15+
int len = nums.size();
16+
long long k = ((long long)len * (len + 1) / 2 + 1) / 2;
17+
18+
auto check = [&](int upper) {
19+
long long cnt = 0;
20+
int l = 0;
21+
unordered_map<int, int> freq;
22+
for (int r = 0; r < len; r++) {
23+
freq[nums[r]]++; // expand right
24+
while (freq.size() > upper) { // too many elements in window
25+
int out = nums[l++];
26+
if (--freq[out] == 0) { // out left
27+
freq.erase(out);
28+
}
29+
}
30+
cnt += r - l + 1; // right is r, r - l + 1
31+
if (cnt >= k) {
32+
return true;
33+
}
34+
}
35+
return false;
36+
};
37+
int le = 0, ri = len;
38+
while (le + 1 < ri) {
39+
int mid = (le + ri) / 2;
40+
(check(mid) ? ri : le) = mid;
41+
}
42+
return ri;
43+
}
44+
};

format.sh

+3-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
PROJECT_DIR="./daily"
44

5-
find $PROJECT_DIR -name uthash -prune -o -name "*.cpp" -o -name "*.c" -o -name "*.h" | xargs clang-format -i
5+
# find $PROJECT_DIR -name uthash -prune -o -name "*.cpp" -o -name "*.c" -o -name "*.h" | xargs clang-format -i
6+
7+
find $PROJECT_DIR -name uthash -prune -o \( -name "*.cpp" -o -name "*.c" -o -name "*.h" \) -print0 | xargs -0 clang-format -i
68

79
git add --all

0 commit comments

Comments
 (0)