【LeetCode candy】
来源:互联网 发布:网络信息安全宣传标语 编辑:程序博客网 时间:2024/05/21 21:41
135.Candy
解题思路
我首先想到的是如果序列是递增的,那么序列的值是逐渐递增的。如果序列是递减的,那么从最小的开始,往回来是递增的。如果遇到相等,就是1。
class Solution { public int candy(int[] ratings) { if (ratings.length == 1){ return 1; } int[] res = new int[ratings.length]; res[0] = 1; for (int i = 1; i < ratings.length; i++){ if (ratings[i] >= ratings[i-1]){ int start = i-1; while (i < ratings.length && ratings[i] >= ratings[i-1]){ i++; } int k = 1; for (int j = start; j < i-1; j++){ if (ratings[j] < ratings[j+1]){ res[j] = k; k++; } else { if (j - 1 < 0){ res[j] = 1; continue; } if (ratings[j] > ratings[j-1]){ res[j] = k; k = 1; continue; } res[j] = 1; //k = 1; } } res[i-1] = k; i--; } if (ratings[i] < ratings[i-1]){ int start = i-1; while (i < ratings.length && ratings[i] <= ratings[i-1]){ i++; } int k = 1; for (int j = i-1; j > start; j--){ if (ratings[j] < ratings[j-1]){ res[j] = k; k++; } else { if (j + 1 >= i){ res[j] = 1; continue; } if (ratings[j] < ratings[j+1]){ res[j] = k; k = 1; continue; } res[j] = 1; //k = 1; } } res[start] = Math.max(k, res[start]); i--; continue; } } int sum = 0; for (int i = 0; i < res.length; i++){ sum += res[i]; } return sum; }}
但是最后一个例子没有通过,说明还是有问题。
在网上看了一个新的思路,就是从左边往右边遍历,如果遇到右边比左边大,则右边比左边结果加1。然后从右边遍历,如果左边比右边大,如果左边结果小于右边结果,那么左边结果为右边结果加1。
其实在前一个思路中已经有一些端倪,可以通过往回遍历修改当前值了。其实上一个思路是这个思路的复杂实现。同样是遇到上升加1,遇到相等边为1,遇到下降往回遍历修改。那么既然是互相不干扰,可以分别便来实现。
代码如下
public class Candy { public int candy(int[] ratings) { int size = ratings.length; if (size == 0){ return 0; } if (size == 1){ return 1; } int[] res = new int[size]; res[0] = 1; for (int i = 1; i < size; i++){ if (ratings[i] > ratings[i-1]){ res[i] = res[i-1] + 1; } else { res[i] = 1; } } for (int i = size-2; i >= 0; i--){ if (ratings[i] > ratings[i+1]){ res[i] = Math.max(res[i], res[i+1] + 1); } } int sum = 0; for (int i = 0; i < size; i++){ sum += res[i]; } return sum; }}
阅读全文
0 0
- Leetcode: Candy
- LeetCode:Candy
- [leetcode]Candy
- Leetcode: Candy
- 【leetcode】Candy
- LeetCode:Candy
- [LeetCode] Candy
- [LeetCode]Candy
- [LeetCode] Candy
- 【LeetCode】Candy
- LeetCode | Candy
- Leetcode: Candy
- Candy - LeetCode
- leetcode Candy
- LeetCode Candy
- candy leetcode
- Candy -- LeetCode
- [LeetCode] Candy
- 图像识别中的深度学习
- 【dede】织梦自定义表单
- SVN学习(2)—SVN的简单操作(上)
- jetty部署Java工程
- C++一个标准类的学习
- 【LeetCode candy】
- 总结
- 为接口生成javadoc(eclipse)
- 30、进程的基础理论,并发
- 如何查看java源码中的native方法源码
- 使用okhttp时没有返回正常数据
- 日夜间模式+文字+图片切换
- PDF文档如何添加图片签名
- 封装好的一个的Toast工具类(可以直接调用)