Bootstrap

904.水果成篮

题目介绍

在这里插入图片描述

解题方法

题目翻译成人话就是 :找包含两种元素的最长子串,返回其长度,和2958题的区别是:本题是找种类最多为2,上题是单个种类个数最多为k。

法一:

class Solution {
    public int totalFruit(int[] fruits) {
        int n = fruits.length;
        Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        int left = 0, res = 0;
        for (int right = 0; right < n; ++right) {
            //存储这个窗口内的数以及出现的次数
            hashMap.put(fruits[right], hashMap.getOrDefault(fruits[right], 0) + 1);
            //动态调节滑动窗口的起始位置
            while (hashMap.size() > 2) {
                hashMap.put(fruits[left], hashMap.get(fruits[left]) - 1);
                //出现次数减小为0时需要将对应的键值对从哈希表中移除
                if (hashMap.get(fruits[left]) == 0) {
                    hashMap.remove(fruits[left]);
                }
                left++;
            }
            res = Math.max(res, right - left + 1);
        }
        return res;
    }
}

法二:和jzh一起想出来的,可以减少时间复杂度

class Solution {
    public int totalFruit(int[] fruits) {
        Map<Integer, Integer> map = new HashMap<>();
        int n = fruits.length, ans = 0;
        for (int l = 0, r = 0; r < n; r++) {
            // map的值是记录每个键最后一次出现的位置
            if (map.containsKey(fruits[r])) {
                map.replace(fruits[r], r);
            } else {
                map.put(fruits[r], r);
            }            
            if (map.size() > 2) {
                // 如[1,0,1,4],右指针指到第三个位置4的时候
                // 此时有三种种类,要去掉前面两个种类之一
                // 因为返回最长子串,根据最后一次出现的位置,所以去掉最后一次出现靠前的那一种类
                Set<Integer> keys = map.keySet();
                int idx = n + 1;
                for (Integer key : keys) {
                    if(key == fruits[r]){
                        continue;
                    }
                    idx = Math.min(idx, map.get(key));
                }
                l = idx + 1;
                map.remove(fruits[idx]);
            }
            ans = Math.max(ans, r - l + 1);
        }
        return ans;
    }
}
;