在一排树中,第 i 棵树产生 tree[i] 型的水果。
你可以从你选择的任何树开始,然后重复执行以下步骤:
把这棵树上的水果放进你的篮子里。如果你做不到,就停下来。
移动到当前树右侧的下一棵树。如果右边没有树,就停下来。
请注意,在选择一颗树后,你没有任何选择:你必须执行步骤 1,然后执行步骤 2,然后返回步骤 1,然后执行步骤 2,依此类推,直至停止。
你有两个篮子,每个篮子可以携带任何数量的水果,但你希望每个篮子只携带一种类型的水果。
用这个程序你能收集的水果总量是多少
这道题我利用HashMap+双指针,因为所要求的结果一定是一个字串,所以可以用双指针,HashMap用来判断出现过没有
/**
* @author sanmu
* @classname Solution
* @description 水果成篮
* @date 2020/6/23 20:32
*/
public class Solution {
public int totalFruit(int[] tree) {
if(tree.length == 1){
return 1;
}
int i = 0;
int j = 1;
int temp = i;
int max = 0;
HashMap<String,Integer> hashMap = new HashMap<>(16);
while(i < tree.length && j < tree.length){
if(temp == j){
j++;
}
if(hashMap.isEmpty()){
hashMap.put(String.valueOf(tree[temp]),1);
temp++;
continue;
}
if( (!hashMap.containsKey(String.valueOf(tree[temp])) && hashMap.keySet().size() == 2) ){
max = Math.max(max,temp - i);
i++;
temp = i;
hashMap.clear();
continue;
}else if(!hashMap.containsKey(String.valueOf(tree[temp])) && hashMap.keySet().size() == 1){
hashMap.put(String.valueOf(tree[temp]),1);
temp++;
}else{
temp++;
}
}
if(hashMap.containsKey(String.valueOf(tree[j-1])) && j == tree.length){
max = Math.max(max,temp - i);
}
return max;
}
}
AC截图