Skip to content

Instantly share code, notes, and snippets.

@ducalpha
Created May 22, 2016 15:51
Show Gist options
  • Save ducalpha/62949ac5a9e0289eb70aeae75cb40f69 to your computer and use it in GitHub Desktop.
Save ducalpha/62949ac5a9e0289eb70aeae75cb40f69 to your computer and use it in GitHub Desktop.
Check all ranges of k in an array
#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