Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #include <unordered_map>
- #include <unordered_set>
- using namespace std;
- // (3, 1, 5)
- // [2, 1, 0, 4, 1, 6, 5, 2, 3, 8, 1, 5, 1, 3, 2, 3, 4, 5]
- // | |
- // b e
- // 5:1
- // 3:1
- // 1:1
- // 2:1
- // 8:1
- size_t min_length(const vector<int>& input, const unordered_set<int>& target) {
- if (target.empty()) {
- return 0;
- }
- size_t b = 0; // inclusive
- size_t e = 0; // exclusive
- size_t res = numeric_limits<int>::max();
- unordered_map<int, int> num2freq;
- // (3, 1, 5)
- // [2, 1, 0, 4, *1, 6, 5, 2, 3, 8, 1, 5, 1, 3, 2, 3, 4, 5]
- // b = 0
- // e = 0-1-2
- // {
- // 5: 1
- // 3: 1
- // }
- while (b <= e && e <= input.size()) {
- // shrinking mode
- if (num2freq.size() == target.size()) {
- int num = input[b++];
- auto it = num2freq.find(num);
- if (it != num2freq.end()) {
- it->second--;
- if (it->second == 0) {
- num2freq.erase(it);
- }
- }
- } else {
- if (e == input.size()) {
- break;
- }
- int num = input[e++];
- if (target.count(num) > 0) {
- num2freq[num]++;
- }
- }
- if (num2freq.size() == target.size()) {
- res = min(res, e-b);
- }
- }
- return res;
- }
- // [{2}, {1,2}, {0,1,2}, ...
- //
- // (3, 1)
- // [2, 3, 2, 3, 1, 0]
- // [{2}, {2,3}, {2,3}, {2,3}, {1,2,3}, {0,1,2,3}]
- // [ {0,1,2,3} {0,1,3} {0,1} {0}
- // (3, 1)
- // [2, 3, 2, 3, 1]
- // {3,1} {1} {3,1} {1} {3}
- // 1(N) -> [2] [3] [2] [3] [1]
- // 1(N-1) -> [2,3] [3,2] [2,3] [3,1] <-- 2
- // 1(N-2) -> [2,3,2] ....
- // ...
- // N(1)
- // S = (a1+an)*n / 2
- // S = (1+N)*N / 2
- // O(N^2)
- // vector<int>, unordered_set<int> -> length
- //
- int main() {
- cout << min_length({2, 3, 2, 3, 1}, {3,1}) << endl;
- cout << min_length({2, 1, 0, 4, 1, 6, 5, 2, 3, 8, 1, 5, 0, 1, 3, 2, 3, 4, 5, 1, 3}, {3,1,5,98}) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement