当前位置:   article > 正文

力扣 904.水果成篮

力扣 904.水果成篮

题目:
在这里插入图片描述
题目理解: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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/680364
推荐阅读
相关标签
  

闽ICP备14008679号