Leetcode第904题
题目:
在一排树中,第 i 棵树产生 tree[i] 型的水果。你可以从你选择的任何树开始,然后重复执行以下步骤:
- 把这棵树上的水果放进你的篮子里。如果你做不到,就停下来。
- 移动到当前树右侧的下一棵树。如果右边没有树,就停下来。
请注意,在选择一颗树后,你没有任何选择:你必须执行步骤 1,然后执行步骤 2,然后返回步骤 1,然后执行步骤 2,依此类推,直至停止。
你有两个篮子,每个篮子可以携带任何数量的水果,但你希望每个篮子只携带一种类型的水果。
用这个程序你能收集的水果树的最大总量是多少?
思路:
- 该问题可以简化为:求数组中只包含2个数的子序列的最大长度。
- 解题方法为:可用双指针解决。用两个指针分别指向两个不同的水果,并移动后面的指针,判断是否遇到了新的水果,如果没有新水果出现,那么计数值加1;如果遇到新的水果,那么将前面的指针向后移动,并将后面的指针指向新的水果。
代码:
/*
* @lc app=leetcode.cn id=904 lang=java
*
* [904] 水果成篮
*/
// @lc code=start
class Solution
{
public int totalFruit(int[] fruits)
{
int lastFruit = fruits[0];//保存最后一个水果
int secondLastFruit = fruits[0];//保存倒数第二种水果
int lastFruitCnt = 0;//计数最后一种水果的数量
int max = 0;//返回结果
int curMax = 0;//当前序列的长度
for (int fruit : fruits)
{
//如果是lastFruit或者secondLastFruit,curMax加1
if (fruit == lastFruit || fruit == secondLastFruit)
{
curMax++;
}
//否则,当前curMax为lastFruit和新添加的水果的数量
else
{
curMax = lastFruitCnt + 1;
}
//当前fruit和lastFruit相同
if (fruit == lastFruit)
{
lastFruitCnt++;
}
//如果不同,则需要移动lastFruitCnt和secondLastFruit的位置
else
{
lastFruitCnt = 1;
secondLastFruit = lastFruit;
lastFruit = fruit;
}
max = Integer.max(max, curMax);
}
return max;
}
}