0
点赞
收藏
分享

微信扫一扫

Linux Shell文件描述符和重定向

Alex富贵 2024-04-07 阅读 10

题目:
在这里插入图片描述
题目理解:fruits里的每个数字表示一种类型水果,相同数字表示同种类型水果。

class Solution {
    public int totalFruit(int[] fruits) {
    	// 用HashMap来表示篮子,key表示水果类型,value表示多少颗树
        Map<Integer, Integer> map = new HashMap<>();
        int ans = 0;
        // i表示所求的窗口最右端值,j表示窗口的最左端值
        for (int i = 0, j = 0; i < fruits.length; i++){
            int x = fruits[i];
            map.put(x, map.getOrDefault(x, 0) + 1);
            // 一旦篮子里的类型超过两种,就要开始移窗口的最左端值,即j
            while (map.size() > 2){
                int y = fruits[j];
                j++;
                map.put(y, map.get(y) - 1);  // HashMap不允许key重复,所以这块会用新的值替换掉原来键对应的值
                if (map.get(y) == 0)
                    map.remove(y);
            }
            ans = Math.max(ans, i - j + 1);
        }
        return ans;
    }
}
举报

相关推荐

0 条评论