给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}
及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}
; 针对数组{2,3,4,2,6,2,5,1}
的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}
。
双向链表,小了则移除,压入潜在最大值的下标,滑出则移除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public: vector<int> maxInWindows(const vector<int>& num, unsigned int size) { vector<int> result; deque<int> tower; result.reserve(num.size() - size + 1); for (int i = 0; i < num.size(); i++) { while (tower.size() > 0 && num[tower.back()] < num[i]) { tower.pop_back(); } while (tower.size() > 0 && i - tower.front() >= size ) { tower.pop_front(); } tower.push_back(i); if (i >= size - 1) { result.push_back(num[tower.front()]); } } return result; } };
|