赞
踩
题目:
题目理解: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; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。