1894:找到需要补充粉笔的学生编号

This commit is contained in:
huangge1199 2021-09-10 13:51:13 +08:00
parent 0179848761
commit d4c98419df
2 changed files with 45 additions and 27 deletions

View File

@ -51,8 +51,9 @@
// Related Topics 数组 二分查找 前缀和 模拟 👍 4 👎 0 // Related Topics 数组 二分查找 前缀和 模拟 👍 4 👎 0
package leetcode.editor.cn; package leetcode.editor.cn;
//1894:找到需要补充粉笔的学生编号 //1894:找到需要补充粉笔的学生编号
class FindTheStudentThatWillReplaceTheChalk{ class FindTheStudentThatWillReplaceTheChalk {
public static void main(String[] args) { public static void main(String[] args) {
//测试代码 //测试代码
Solution solution = new FindTheStudentThatWillReplaceTheChalk().new Solution(); Solution solution = new FindTheStudentThatWillReplaceTheChalk().new Solution();
@ -60,35 +61,52 @@ class FindTheStudentThatWillReplaceTheChalk{
//力扣代码 //力扣代码
//leetcode submit region begin(Prohibit modification and deletion) //leetcode submit region begin(Prohibit modification and deletion)
class Solution { class Solution {
public int chalkReplacer(int[] chalk, int k) { // public int chalkReplacer(int[] chalk, int k) {
int temp = k; // int temp = k;
int length = chalk.length; // int length = chalk.length;
int[] free = new int[length]; // int[] free = new int[length];
for (int i = 0; i < length; i++) { // for (int i = 0; i < length; i++) {
if (i == 0) { // if (i == 0) {
free[i] = chalk[i]; // free[i] = chalk[i];
} else { // } else {
free[i] += chalk[i] + free[i - 1]; // free[i] += chalk[i] + free[i - 1];
// }
// temp -= chalk[i];
// if (temp < 0) {
// return i;
// }
// }
// temp %= free[length - 1];
// if (temp == 0) {
// return 0;
// }
// for (int i = 0; i < length; i++) {
// temp -= chalk[i];
// if (temp < 0) {
// return i;
// }
// }
// return 0;
// }
public int chalkReplacer(int[] chalk, int k) {
int size = chalk.length;
int sum = 0;
int i = 0;
for (; i < size && sum <= k; i++) {
sum += chalk[i];
} }
temp -= chalk[i]; if (i < size) {
if (temp < 0) { return i - 1;
return i;
} }
} k %= sum;
temp %= free[length - 1]; i = 0;
if (temp == 0) { for (; i < size && k >= 0; i++) {
return 0; k -= chalk[i];
}
for (int i = 0; i < length; i++) {
temp -= chalk[i];
if (temp < 0) {
return i;
} }
return i - 1;
} }
return 0;
} }
}
//leetcode submit region end(Prohibit modification and deletion) //leetcode submit region end(Prohibit modification and deletion)
} }

File diff suppressed because one or more lines are too long