Created
May 22, 2016 15:51
-
-
Save ducalpha/62949ac5a9e0289eb70aeae75cb40f69 to your computer and use it in GitHub Desktop.
Check all ranges of k in an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <my_epi/common.h> | |
void PrintCache(const multiset<int>& cache) { | |
for (int i : cache) { | |
cout << i << ' '; | |
} | |
cout << endl; | |
} | |
void CheckRange(const vector<int>& nums, int k) { | |
if (k <= 0) | |
return; | |
multiset<int> cache; | |
for (size_t i = 1; i <= k && i < nums.size(); ++i) { | |
cache.emplace(nums[i]); | |
} | |
PrintCache(cache); | |
for (int i = 1; i < nums.size(); ++i) { | |
if (i + k < nums.size()) | |
cache.emplace(nums[i + k]); | |
cache.erase(cache.find(nums[i])); | |
cache.emplace(nums[i - 1]); | |
if (i - k - 1 >= 0) | |
cache.erase(nums[i - k - 1]); | |
PrintCache(cache); | |
} | |
} | |
int main() { | |
vector<int> nums{1, 2, 3, 4, 5, 6, 7, 8}; | |
int k = 2; | |
CheckRange(nums, k); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment