Two Pointers - 前向型指针summary

这类题中,Brute Force是扫两次,On2的复杂度。而Brute Force重复计算了元素,所以可以用Two Pointers来优化。

Minimum Size Subarray Sum:

int minimumSize(vector &nums, int s) {
        // write your code here
        if(nums.empty()) return s == 0 ? 0 : -1;
        int start = 0, min_len = nums.size()+1;
        int sum = 0;
        for(int i=0; i= s){
                min_len = min(min_len, i-start+1);
                sum -= nums[start++];
            }
        }
        return min_len == nums.size() + 1 ? -1 : min_len;
    }

Longest Substring Without Repeating Characters:

int lengthOfLongestSubstring(string s) {
        if(s.empty()) return 0;
        unordered_map mp;
        int start = 0, max_len = 0;
        for(int i=0; i

Longest Substring with At Most K Distinct Characters:

int lengthOfLongestSubstringKDistinct(string s, int k) {
        // write your code here
        if(s.empty() || k <= 0) return 0;
        int start = 0, max_len = 0;
        unordered_map mp;
        for(int i=0; i k){
                if(--mp[s[start]] == 0) mp.erase(s[start]);
                start++;
            }
            max_len = max(max_len, i-start+1);
        }
        return max_len;
    }

Minimum Window Substring:

string minWindow(string &source, string &target) {
        // write your code here
        unordered_map mp;
        for(int i=0; i= 0) cnt++;
            }
            while(cnt == target.length()){
                if(i-left+1 < min_len){
                    min_len = i-left+1;
                    minLeft = left;
                }
                if(mp.count(source[left])){
                    mp[source[left]]++;
                    if(mp[source[left]] > 0) cnt--;
                }
                left++;
            }
        }
        return min_len == INT_MAX ? "" : source.substr(minLeft, min_len);
    }

你可能感兴趣的:(Two Pointers - 前向型指针summary)