classSolution{publicinttotalFruit(int[] fruits){int left =0;ArrayList<Integer> list1=newArrayList<Integer>();ArrayList<Integer> list2=newArrayList<Integer>();int result =0;for(int right =0; right < fruits.length ; right++){if( list1.size()==0|| list1.contains(fruits[right])){
list1.add(fruits[right]);}elseif( list2.size()==0|| list2.contains(fruits[right])){
list2.add(fruits[right]);}else{while(!(list2.size()==0|| list1.size()==0)){if(list1.contains(fruits[left])){
list1.remove(list1.size()-1);}if(list2.contains(fruits[left])){
list2.remove(list2.size()-1);}
left++;}
right--;
result =Math.max(result, list1.size()+list2.size());}return result;}
复杂度分析
时间复杂度:O(n)
空间复杂度:O(1)
2 使用Map
classSolution{publicinttotalFruit(int[] fruits){int n = fruits.length;Map<Integer,Integer> cnt =newHashMap<Integer,Integer>();int left =0, ans =0;for(int right =0; right < n;++right){
cnt.put(fruits[right], cnt.getOrDefault(fruits[right],0)+1);while(cnt.size()>2){
cnt.put(fruits[left], cnt.get(fruits[left])-1);if(cnt.get(fruits[left])==0){
cnt.remove(fruits[left]);}++left;}
ans =Math.max(ans, right - left +1);}return ans;}}