classSolution { public: intmaxSumTwoNoOverlap(vector<int>& A, int L, int M){ constint n = A.size(); vector<int> sum_l(n, 0); vector<int> sum_m(n, 0); int current_sum = accumulate(A.begin(), A.begin() + L, 0); sum_l.at(0) = current_sum; for (int i = 1; i <= n - L; ++i) { current_sum += A[i + L - 1] - A[i - 1]; sum_l.at(i) = current_sum; } current_sum = accumulate(A.begin(), A.begin() + M, 0); sum_m.at(0) = current_sum; for (int i = 1; i <= n - M; ++i) { current_sum += A[i + M - 1] - A[i - 1]; sum_m.at(i) = current_sum; } int ret = 0; for (int i = 0; i <= n - L; ++i) { for (int j = i + L; j <= n - M; ++j) { ret = max(ret, sum_l.at(i) + sum_m.at(j)); } } for (int i = 0; i <= n - M; ++i) { for (int j = i + M; j <= n - L; ++j) { ret = max(ret, sum_m.at(i) + sum_l.at(j)); } } return ret; } };
One pass的解决方案,思想是 DP。
时间复杂度: O(N),
空间复杂度: O(1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intmaxSumTwoNoOverlap(vector<int>& A, int L, int M){ for (int i = 1; i < A.size(); ++i) { A[i] += A[i - 1]; } // Lmax: 从头到当前位置再向前跳M个元素的子数组中,长度为L的子数组的最大和 // Mmax: ... ... . . .. . L .. . . .. . .. .M.. ... int ret = A[L + M - 1], Lmax = A[L - 1], Mmax = A[M - 1]; for (int i = L + M; i < A.size(); ++i) { Lmax = max(Lmax, A[i - M] - A[i - M - L]); Mmax = max(Mmax, A[i - L] - A[i - L - M]); ret = max({ret, A[i] - A[i - M] + Lmax, A[i] - A[i - L] + Mmax}); } return ret; } };
classStreamChecker { // 单词树 structTrie { vector<shared_ptr<Trie>> data = vector<shared_ptr<Trie>>(26); bool value = false; }; shared_ptr<Trie> root = make_shared<Trie>(); vector<char> history; public: StreamChecker(vector<string>& words) { for (constauto& word : words) { shared_ptr<Trie> t = root; for (int i = word.size() - 1; i >= 0; --i) { char c = word[i]; if (t->data[c - 'a'] == nullptr) t->data[c - 'a'] = make_shared<Trie>(); t = t->data[c - 'a']; } t->value = true; } } boolquery(char letter){ history.push_back(letter); shared_ptr<Trie> current = root; if (current->value) returntrue; for (int i = history.size() - 1; i >= 0; --i) { char c = history[i]; if (current->data[c - 'a'] != nullptr) { current = current->data[c - 'a']; } else { returnfalse; } if (current->value) returntrue; } returnfalse; } };
/** * Your StreamChecker object will be instantiated and called as such: * StreamChecker* obj = new StreamChecker(words); * bool param_1 = obj->query(letter); */
后记
自从春节被快手师兄问C新特性后,已经过去2个半月了。这期间,我看了《C Primer》,正在看《Effective Modern C++》,《C++ Concurrency in Action》。自信对新特性有了更多的了解,也在尝试更多地参与C的项目,把C当作自己的主语言来发展。希望在明年找工作的时候能有所核心竞争力。