[Algorithm Topic Breakthrough] Sliding Window-Fruit into Basket (13)

Table of contents

1. Question analysis

2. Algorithm principle

3. Code writing

Write at the end:


1. Question analysis

Question link: 904. Fruit into basket - Leetcode

The question has a long paragraph, but if we read the question once, we can refine and transform it into the requirements of the question:

In fact, it is to find the longest subarray with no more than two types of numbers in the array.

2. Algorithm principle

This problem can be solved using a sliding window.

why?

We can briefly analyze it,

We maintain a window via a hash table,

Let right++ enter the window. If three types of fruits appear, let left++,

left++ will have two situations,

1. There are still three fruits, so let left continue++

2. There are two kinds of fruits left, then record the results. Now the focus comes.

Does right need to return to the position of left and re++? No, this is the core of the sliding window,

We can just let right continue++ to enter the window.

3. Code writing

class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        unordered_map<int, int> win;
        int kinds = 0, left = 0, right = 0, len = 0;
        while(right < fruits.size()) {
            win[fruits[right++]]++;
            while(left < fruits.size() && win.size() > 2) {
                win[fruits[left++]]--;
                if(win[fruits[left - 1]] == 0) {
                    win.erase(fruits[left - 1]);
                    break;
                }
            }
            len = max(len, right - left);
        }
        return len;
    }
};

Write at the end:

That’s the content of this article, thank you for reading.

If you feel you have gained something, you can give the blogger a like .

If there are omissions or errors in the content of the article, please send a private message to the blogger or point it out in the comment area~

Guess you like

Origin blog.csdn.net/Locky136/article/details/131734640