两次遍历,第一遍将大于等于序列的糖果分好,第二遍反向遍历,将小于序列的糖果分好
需要注意两点
1. 等于的情况,后一个孩子的糖果为1
2. 反向遍历的时候,到已经分了糖果的边界孩子时,需要判断,反向自增的糖果和此孩子之前分的糖果哪个大,取大值
public class Solution { public int candy(int[] ratings) { if(ratings == null || ratings.length == 0){ return 0; } int count = 0; Integer[] counter = new Integer[ratings.length]; counter[0]=1; for(int i=1; i<ratings.length; i++){ Integer pre =ratings[i-1]; int num = ratings[i]; if(num>pre){ if(counter[i-1] == null){ counter[i]=2; }else { counter[i]=counter[i-1]+1; } }else if(num == pre){ counter[i] = 1; } } Integer firstNullIndex = null; for(int i=ratings.length-1; i>=0; i--){ if(counter[i] == null && firstNullIndex==null){ counter[i]=1; firstNullIndex = i; }else if(counter[i]==null && firstNullIndex!=null){ counter[i]=counter[i+1]+1; }else if(counter[i] != null && firstNullIndex!=null){ firstNullIndex = null; counter[i]=((counter[i+1]+1)>counter[i])?counter[i+1]+1:counter[i]; } } for(Integer c : counter){ if(c != null){ count += c; } } return count; } }
相关推荐
LeetCode题解 - Java语言实现-181页.pdf
500195422331430LeetCode题解 - Java语言实现.zip
大佬的leetcode刷题笔记(c++版本)
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
leetcode1-240题中文题解,md格式,java版本 有题目有题解有代码 需要使用markdown打开
leetcode 答案Leetcode-Java - 符合条件(Hacktoberfest) JAVA 中的 Leetcode 答案
leetcode1-300.docx
leetcode leetcode-java 用 Java 编写的 LeetCode 解决方案。 介绍 使用 Java 编写的 LeetCode 解决方案。 en的。 zh为 . 解决方案文章的note 。 标签 问题集
java lru leetcode LeetCode-Tag-Java 解决方案 LeetCode 的解决方案 指数
leetcode题库 leetcode-java 用Java实现leetcode题库
答案leetcode-cn-java-algorithm-solution 我试图找到学习 leetcode 算法的最佳方法,所以我创建了它。 该项目将帮助您更好地学习 Leetcode 算法。 1. 入门 你想知道如何使用吗? 好的,现在让我们开始吧! 1.1 如何...
leetcode-java, 我的LeetCode在线在线判断解决方案 leetcode-java我的 LeetCode在线判断系统的解决方案。插件生成状态 要求Java> = 1.6Gradle> = 1.8.6 ( 1.8.6 是我唯一尝试的版本)生成 Eclipse 项目
然后通过用循环来解:假设第一个for循环是一个数组的循环,而后它的内嵌循环是也是这个数组,只是下标从0变成了1,这样,在第一次循环时,第1个元素会与其他所有元素
leetcode Leetcode-Java-解决方案 Java 中 Leetcode 问题的解决方案
leetcode-java LeetCode Java Solution 题目 : : : : more : : : : : : more : : : 题解 recursion 104题解 解法:递归 复杂度:O(n)、O(h) class Solution { public int maxDepth(TreeNode root) { //...
leetcode 答案Leetcode---数据库 我对 Leetcode 数据库问题的回答