Loading

LEETCODE-904-水果成篮

题目参考:https://leetcode.cn/problems/fruit-into-baskets/
题解参考:https://leetcode.cn/problems/fruit-into-baskets/solution/shen-du-jie-xi-zhe-dao-ti-he-by-linzeyin-6crr/

滑窗模板

给定数组 nums,定义滑窗的左右边界 i, j,求满足某个条件的滑窗长度。

最小滑窗模板:
while j < len(nums):
    判断[i, j]是否满足条件
    while 满足条件:
        不断更新结果(注意在while内更新!)
        i += 1 (最大程度的压缩i,使得滑窗尽可能的小)
    j += 1

最大滑窗模板:
while j < len(nums):
    判断[i, j]是否满足条件
    while 不满足条件:
        i += 1 (最保守的压缩i,一旦满足条件了就退出压缩i的过程,使得滑窗尽可能的大)
    不断更新结果(注意在while外更新!)
    j += 1

我的题解

class Solution {
    public int totalFruit(int[] fruits) {
        // 采摘总数最大数
        int sum = 0;
        // 每一种情况的采摘数
        int num = 0;

        // 篮子
        Set<Integer> basket = new HashSet<>();

        for (int i = 0; i < fruits.length; i++) {
            if (fruits.length <= 2) {
                sum = fruits.length;
                break;
            }

            try {
                // 出现异常表表示已经从左到右走完了
                basket.add(fruits[i]);
                basket.add(fruits[i + 1]);
            } catch (Exception e) {
                break;
            }

            for (int j = i; j < fruits.length; j++) {
                boolean ok = basket.contains(fruits[j]);
                if (ok) {
                    num++;
                } else if (basket.size() < 2) {
                    basket.add(fruits[j]);
                    num++;
                } else {
                    break;
                }
            }
            sum = Math.max(num, sum);
            num = 0;
            basket.clear();
        }

        return sum;
    }
}

其他题解

class Solution {
    public int totalFruit(int[] fruits) {
        // 滑窗左边界
        int left = 0;
        // 滑窗右边界
        int right = 0;
        // 水果类型数
        int count = 0;
        // 最大采摘数
        int max = 0;
        // 篮子数
        int num = 2;

        // 农场果树采摘情况
        Map<Integer, Integer> typeMap = new HashMap<>(fruits.length);
        for (Integer fruit : fruits) {
            typeMap.put(fruit, 0);
        }

        // 移动滑窗右边界
        while (right < fruits.length) {
            // 未出现过的种类,本次收集,对水果类型数+1
            if (typeMap.get(fruits[right]) == 0) {
                count++;
            }

            // 此时进采摘树上的水果
            typeMap.put(fruits[right], typeMap.get(fruits[right]) + 1);

            // 判断是否满足条件(只可收集num种水果)
            while (count > num) {
                // 此处进行滑窗左边界的压缩(最保守的压缩,一旦满足了条件即:count种类<=可收集的水果种类数,就退出压缩左边界即跳出while)
                if (typeMap.get(fruits[left]) == 1) {
                    count--;
                }
                typeMap.put(fruits[left], typeMap.get(fruits[left]) - 1);
                left++;
            }
            max = Math.max(max, right - left + 1);
            right++;
        }
        return max;
    }
}

posted @ 2022-08-01 14:07  溫柔の風  阅读(21)  评论(0编辑  收藏  举报