LeetCode 904. 水果成篮

题目描述

904. 水果成篮

思路分析

解法一:滑动窗口(推荐)

核心思路

  • 维护窗口内最多两种水果。
  • 若种类超过 2,则移动左指针缩小窗口。
  • 记录窗口最大长度。


复杂度分析

  • 时间复杂度:O(n),其中 n 表示数组长度。
  • 空间复杂度:O(1)。
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int totalFruit(int[] fruits) {
        Map<Integer, Integer> count = new HashMap<>();
        int left = 0;
        int res = 0;

        for (int right = 0; right < fruits.length; right++) {
            count.put(fruits[right], count.getOrDefault(fruits[right], 0) + 1);
            while (count.size() > 2) {
                count.put(fruits[left], count.get(fruits[left]) - 1);
                if (count.get(fruits[left]) == 0) {
                    count.remove(fruits[left]);
                }
                left++;
            }
            res = Math.max(res, right - left + 1);
        }

        return res;
    }
}
func totalFruit(fruits []int) int {
	count := make(map[int]int)
	left := 0
	res := 0

	for right, val := range fruits {
		count[val]++
		for len(count) > 2 {
			count[fruits[left]]--
			if count[fruits[left]] == 0 {
				delete(count, fruits[left])
			}
			left++
		}
		if right-left+1 > res {
			res = right - left + 1
		}
	}

	return res
}

相似题目

题目 难度 考察点
340. 至多包含 K 个不同字符的最长子串 困难 滑动窗口
992. K 个不同整数的子数组 困难 滑动窗口
1004. 最大连续1的个数 III 中等 滑动窗口
3. 无重复字符的最长子串 中等 滑动窗口
424. 替换后的最长重复字符 中等 滑动窗口
本文作者:
本文链接: https://hgnulb.github.io/blog/2024/85039853
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!