本文主要是介绍LeetCode 每日一题 ---- 【2105. 给植物浇水 II】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
LeetCode 每日一题 ---- 【2105. 给植物浇水 II】
- 2105.给植物浇水II
- 方法:模拟+双指针
2105.给植物浇水II
方法:模拟+双指针
今天是给植物浇水II,昨天是I,本质上和昨天的没有区别,都是模拟,今天额外需要注意的就是需要用一下双指针,其实题目的描述就是双指针了,所以一般情况下都会用到。。。
class Solution {public int minimumRefill(int[] plants, int capacityA, int capacityB) {int len = plants.length;int ans = 0;int waterA = capacityA, waterB = capacityB;for (int i = 0, j = len - 1; i < len && j >= 0 && i <= j; i ++ , j -- ) {if (i == j) {if (waterA >= waterB) {if (waterA >= plants[i]) {waterA -= plants[i];} else {waterA = capacityA;waterA -= plants[i];ans ++ ;}} else {if (waterB >= plants[j]) {waterB -= plants[i];} else {waterB = capacityB;waterB -= plants[i];ans ++ ;}}continue;}if (waterA >= plants[i]) {waterA -= plants[i];} else {waterA = capacityA;waterA -= plants[i];ans ++ ;}if (waterB >= plants[j]) {waterB -= plants[j];} else {waterB = capacityB;waterB -= plants[j];ans ++ ;}}return ans;}
}
时间复杂度:
O(n)
空间复杂度:
O(1)
这篇关于LeetCode 每日一题 ---- 【2105. 给植物浇水 II】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!