博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 904. Fruit Into Baskets
阅读量:6417 次
发布时间:2019-06-23

本文共 1868 字,大约阅读时间需要 6 分钟。

Problem

In a row of trees, the i-th tree produces fruit with type tree[i].

You start at any tree of your choice, then repeatedly perform the following steps:

Add one piece of fruit from this tree to your baskets. If you cannot, stop.

Move to the next tree to the right of the current tree. If there is no tree to the right, stop.
Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.

You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.

What is the total amount of fruit you can collect with this procedure?

Example 1:

Input: [1,2,1]Output: 3Explanation: We can collect [1,2,1].

Example 2:

Input: [0,1,2,2]Output: 3Explanation: We can collect [1,2,2].If we started at the first tree, we would only collect [0, 1].

Example 3:

Input: [1,2,3,2,2]Output: 4Explanation: We can collect [2,3,2,2].If we started at the first tree, we would only collect [1, 2].

Example 4:

Input: [3,3,3,1,2,1,1,2,3,3,4]Output: 5Explanation: We can collect [1,2,1,1,2].If we started at the first tree or the eighth tree, we would only collect 4 fruits.

Note:

1 <= tree.length <= 400000 <= tree[i] < tree.length

Solution

class Solution {    public int totalFruit(int[] tree) {        if (tree.length <= 2) return tree.length;        Map
map = new HashMap<>(); int start = 0, max = 0; for (int i = 0; i < tree.length; i++) { map.put(tree[i], map.getOrDefault(tree[i], 0)+1); while (map.size() > 2) { map.put(tree[start], map.get(tree[start])-1); if (map.get(tree[start]) == 0) map.remove(tree[start]); start++; } max = Math.max(max, i-start+1); } return max; }}

转载地址:http://bqpra.baihongyu.com/

你可能感兴趣的文章
讨论:今日头条适配方案使用中出现的问题
查看>>
CSS3 3D翻转动画
查看>>
要命啦!Word中快速录入大全,内含快捷键小技巧,快来一起学习!
查看>>
javascript实现音频mp3播放
查看>>
html5-离线缓存
查看>>
linux系统安装完后的常见工作
查看>>
在Linux服务器、客户端中构建密钥对验证进行远程连接
查看>>
揪出MySQL磁盘消耗迅猛的真凶
查看>>
和“C”的再遇
查看>>
一键安装kubernetes 1.13.0 集群
查看>>
RabbitMq的集群搭建
查看>>
spring boot + mybatis 同时访问多数据源
查看>>
URL中汉字转码
查看>>
[转]go正则实例
查看>>
Selector中关于顺序的注意事项
查看>>
小黑小波比.清空<div>标签内容
查看>>
Java中的ExceptionInInitializerError异常及解决方法
查看>>
Spring 注入bean时的初始化和销毁操作
查看>>
java线程同步原理(lock,synchronized)
查看>>
MyEclipse中使用Hql编辑器找不到Hibernate.cfg.xml文件解决方法
查看>>