Advertisement
seulunga

Untitled

Feb 19th, 2019
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <unordered_map>
  5. #include <unordered_set>
  6.  
  7. using namespace std;
  8.  
  9. // (3, 1, 5)
  10. // [2, 1, 0, 4, 1, 6, 5, 2, 3, 8, 1, 5, 1, 3, 2, 3, 4, 5]
  11. //                          |        |
  12. //                          b        e
  13. // 5:1
  14. // 3:1
  15. // 1:1  
  16.  
  17. // 2:1
  18. // 8:1
  19.  
  20. size_t min_length(const vector<int>& input, const unordered_set<int>& target) {
  21.   if (target.empty()) {
  22.     return 0;
  23.   }
  24.   size_t b = 0; // inclusive
  25.   size_t e = 0; // exclusive
  26.   size_t res = numeric_limits<int>::max();
  27.   unordered_map<int, int> num2freq;
  28. // (3, 1, 5)
  29.   // [2, 1, 0, 4, *1, 6, 5, 2, 3, 8, 1, 5, 1, 3, 2, 3, 4, 5]  
  30.   // b = 0
  31.   // e = 0-1-2
  32.   // {
  33.  
  34.   // 5: 1
  35.   // 3: 1
  36.   // }
  37.   while (b <= e && e <= input.size()) {
  38.     // shrinking mode
  39.     if (num2freq.size() == target.size()) {
  40.       int num = input[b++];
  41.       auto it = num2freq.find(num);
  42.       if (it != num2freq.end()) {
  43.         it->second--;
  44.         if (it->second == 0) {
  45.           num2freq.erase(it);
  46.         }
  47.       }
  48.     } else {
  49.       if (e == input.size()) {
  50.         break;
  51.       }
  52.       int num = input[e++];
  53.       if (target.count(num) > 0) {
  54.         num2freq[num]++;
  55.       }
  56.     }
  57.     if (num2freq.size() == target.size()) {
  58.       res = min(res, e-b);
  59.     }
  60.   }
  61.   return res;
  62. }
  63.  
  64.  
  65. // [{2}, {1,2}, {0,1,2}, ...
  66. //
  67. // (3, 1)
  68. // [2,   3,      2,    3,     1,        0]
  69. // [{2}, {2,3}, {2,3}, {2,3}, {1,2,3}, {0,1,2,3}]
  70. // [          {0,1,2,3}  {0,1,3}   {0,1}   {0}
  71.  
  72. // (3, 1)
  73. // [2, 3, 2, 3, 1]
  74. //           {3,1} {1}   {3,1} {1}   {3}
  75. // 1(N)   -> [2]   [3]   [2]   [3]   [1]
  76. // 1(N-1) -> [2,3] [3,2] [2,3] [3,1] <-- 2
  77. // 1(N-2) -> [2,3,2] ....  
  78. // ...
  79. // N(1)      
  80. // S = (a1+an)*n / 2
  81. // S = (1+N)*N / 2
  82. // O(N^2)
  83.  
  84. // vector<int>, unordered_set<int> -> length
  85. //
  86.  
  87. int main() {
  88.   cout << min_length({2, 3, 2, 3, 1}, {3,1}) << endl;
  89.   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;
  90.   return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement