问题描述
小U最近沉迷于一款养成类游戏,游戏中的角色拥有三项属性:体力、智力和武力,初始值均为0。随着每天的游戏进展,这些属性会逐步增加。增加情况由一个二维数组 growup 表示,每个元素是一个长度为3的一维数组,分别表示每天的体力、智力和武力增加值。例如,[[1, 1, 2], [2, 2, 1], [2, 1, 2]] 表示第一天体力增加1,智力增加1,武力增加2,第二天分别增加2,2,1,第三天分别增加2,1,2。
在游戏中,玩家可以通过学习新技能来增强角色,但前提是角色的三项属性必须达到技能学习的要求。每个技能的学习要求也用一个二维数组 skill 表示,数组中的每个元素是一个长度为3的一维数组,分别表示学习某个技能所需的最低体力、智力和武力值。
任务是根据 growup 和 skill 数组,计算出玩家在多少天内可以学习每个技能。如果无法满足某个技能的学习要求,则返回 -1。
测试样例
样例1:
输入:m = 3, n = 3, arrayM = [[1, 3, 3], [2, 5, 6], [3, 3, 1]], arrayN = [[1, 1, 1], [4, 5, 5], [7, 7, 7]]
输出:[1, 3, -1]
样例2:
输入:m = 2, n = 2, arrayM = [[2, 4, 1], [3, 1, 2]], arrayN = [[3, 5, 2], [7, 7, 7]]
输出:[2, -1]
样例3:
输入:m = 2, n = 3, arrayM = [[2, 4, 1], [3, 1, 2]], arrayN = [[3, 5, 2], [7, 7, 7], [4, 4, 4]]
输出:[2, -1,-1]
通过初始化一个记录天数的数组并逐步累加每天的属性增加值,我们可以在每次属性更新后检查每个技能的学习条件是否满足,一旦条件满足即记录对应的天数,如果遍历完所有天数后仍有技能未满足条件,则标记为无法学习,最终返回每个技能的学习天数或无法学习的标记。具体算法实现思路:
- 初始化计数数组:创建一个长度为技能数量的数组
<font style="color:rgb(26, 32, 41);">count</font>,用于记录每个技能可以学习的天数,初始值设为<font style="color:rgb(26, 32, 41);">-1</font>,表示尚未达到学习条件。 - 初始化属性总和数组:创建一个长度为3的数组
<font style="color:rgb(26, 32, 41);">sum</font>,用于累加每天的属性增加值,初始值设为<font style="color:rgb(26, 32, 41);">[0, 0, 0]</font>。 - 遍历每天的增长情况:使用一个循环遍历
<font style="color:rgb(26, 32, 41);">arrayM</font>,对于每一天,将当天的属性增加值累加到<font style="color:rgb(26, 32, 41);">sum</font>数组中。 - 检查技能学习条件:在每天的属性累加后,遍历
<font style="color:rgb(26, 32, 41);">arrayN</font>检查每个技能的学习条件是否满足。如果某个技能的学习条件首次被满足(即<font style="color:rgb(26, 32, 41);">count</font>对应的值为<font style="color:rgb(26, 32, 41);">-1</font>),则记录下当前的天数(<font style="color:rgb(26, 32, 41);">day + 1</font>)到<font style="color:rgb(26, 32, 41);">count</font>数组中。 - 返回结果:在所有天数遍历完毕后,返回
<font style="color:rgb(26, 32, 41);">count</font>数组,它包含了每个技能可以学习的天数或者<font style="color:rgb(26, 32, 41);">-1</font>(如果无法学习)。
public class Main {
public static int[] solution(int m, int n, int[][] arrayM, int[][] arrayN) {
int[] count = new int[n];
for (int i = 0; i < n; i++) {
count[i] = -1;
}
int[] sum = new int[] { 0, 0, 0 };
for (int day = 0; day < m; day++) {
sum[0] += arrayM[day][0];
sum[1] += arrayM[day][1];
sum[2] += arrayM[day][2];
// 检查所有技能是否可以学习
for (int skillIndex = 0; skillIndex < n; skillIndex++) {
if (count[skillIndex] == -1 &&
sum[0] >= arrayN[skillIndex][0] &&
sum[1] >= arrayN[skillIndex][1] &&
sum[2] >= arrayN[skillIndex][2]) {
count[skillIndex] = day + 1;
}
}
}
return count;
}
public static void main(String[] args) {
// Add your test cases here
System.out.println(java.util.Arrays.equals(solution(3, 3, new int[][] { { 1, 3, 3 }, { 2, 5, 6 }, { 3, 3, 1 } },
new int[][] { { 1, 1, 1 }, { 4, 5, 5 }, { 7, 7, 7 } }), new int[] { 1, 3, -1 }));
}
}