滑动窗口解题技巧
1.和為s的連續(xù)正數序列
class Solution { public:vector<vector<int>> findContinuousSequence(int target) {int left = 1;int right = 1;int sum = 0;vector<vector<int>> res;while (left <= target / 2 + 1){if (sum < target){sum+=right;right++;}else if (sum > target) {sum-=left;left++;}else {vector<int> vec;for(int k = left; k <right; k++){vec.push_back(k); }res.push_back(vec);sum-=left;left++;}}return res;} };2.LeetCode239.滑動窗口的最大值
本題我們維護一個雙端隊列,每次對要進來的元素進行判斷,確保雙端隊列從隊頭到隊尾是從大到小,隊頭存放當前窗口的最大值,為了確保是當前窗口最大值,就需要對隊頭進行判斷。deq.front() == nums[i-k]就是檢查是不是當前窗口。
class Solution { public:vector<int> maxSlidingWindow(vector<int>& nums, int k) {vector<int> res;deque<int> deq;int len = nums.size();for(int i = 0; i < len; i++){while (!deq.empty() && deq.back() < nums[i]) deq.pop_back();if (!deq.empty() && i >= k && deq.front() == nums[i-k]) deq.pop_front();deq.push_back(nums[i]);if (i >= k-1) res.push_back(deq.front());}return res;} };2.LeetCode3.最長不含重復字符的字符串
C++(自己思路)
C++(題解)
class Solution { public:int lengthOfLongestSubstring(string s) {map<char,int> map;int size = s.size();int result=0;for (int left = 0, right = 0; right < size; right++) {if(map.find(s[right])!=map.end()) {left =max(map[s[right]]+1, left);}result = max(result, right - left + 1);map[s[right]] = right;}return result;} };C++終極簡化版:
class Solution { public:int lengthOfLongestSubstring(string s) {int arr[256]={0};int size = s.size();int result=0;for (int left = 0, right = 0; right < size; right++) {char c=s[right];left=max(arr[c],left);result=max(result,right-left+1);arr[c]=right+1;}return result;} };3.LeetCode438.找到字符串中所有字母異位詞
class Solution { public:vector<int> findAnagrams(string s, string p) {int sSize = (int)s.size();int pSize = (int)p.size();if(sSize < pSize) return {};vector<int> rs;vector<int> needs(26,0); //pvector<int> window(26,0); //sfor (char c : p) needs[c - 'a']++;int left = 0, right = 0;while (right < sSize) {char charR = s[right++];window[charR - 'a']++;while (window[charR - 'a'] > needs[charR - 'a']) {char charL = s[left];window[charL - 'a']--;left++;}if (right - left == pSize) {rs.push_back(left);}}return rs;} };總結
- 上一篇: 计组第三章系统总线自我总结
- 下一篇: 二叉树解题套路