题解 | #大胃王牛牛# java
大胃王牛牛
https://www.nowcoder.com/practice/4e55777e218b4850928d054a8cddaf50
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param grass int整型一维数组
* @param cost int整型一维数组
* @return int整型
*/
public int can_complete_circuit (int[] grass, int[] cost) {
// write code here
int n = grass.length;
for (int start = 0; start < n; start++) {
int totalGrass = 0;
int totalCost = 0;
boolean canComplete = true;
for (int i = 0; i < n; i++) {
int index = (start + i) % n;
totalGrass += grass[index];
totalCost += cost[index];
if (totalCost > totalGrass) {
canComplete = false;
break;
}
}
if (canComplete) {
return start + 1; // 返回下标,从1开始计数
}
}
return -1;
}
}
Java 编程语言。
该题考察了以下知识点:
- 循环遍历
- 索引计算
代码的文字解释如下:
- 获取牛棚的数量 n。
- 使用外层循环遍历每个牛棚作为起点,将起点索引标记为
start。 - 在内层循环中,模拟从起点出发走完环形路线的过程,使用
index记录当前所在牛棚的索引。 - 计算总草料
totalGrass和总消耗totalCost分别累加草料和消耗。 - 如果在某个牛棚处总消耗超过总草料,说明无法走完环形路线,将
canComplete标记为 false 并中断循环。 - 如果
canComplete仍然为 true,表示可以走完环形路线,返回当前起点索引加1(从1开始计数)。 - 如果所有起点都无法完成,返回 -1 表示无解。