This is the question of the day for 2021-9-10 in LeetCode: “1894. Find the Student number that needs chalk to be added”
1. Topic description
There are n students in a class, numbered from 0 to N-1. Each student will answer the questions in turn, with student 0 first, then student 1, and so on, until student N-1, and then the teacher will repeat the process, starting with student 0 again.
You are given an array of integers with length N and subscripts starting from 0 chalk and an integer k. I started with k pieces of chalk in my pencil box. When student I answers the question, he will consume chalk[I]. If the amount of chalk left is strictly less than Chalk [I], student I needs to replenish chalk.
Please return the number of the student whose chalk needs replenishing.
Example 1:
Input: chalk = [5,1,5], k = 22 Output: 0 explanation: the students consume chalk as follows: - the student numbered 0 uses 5 pieces of chalk, then k = 17. - Student number 1 uses 1 piece of chalk, and then k = 16. - Student 2 uses 5 pieces of chalk, and then k = 11. - Student 0 uses 5 pieces of chalk, and k = 6. - Student number 1 uses 1 piece of chalk, and then k = 5. - Student number 2 uses 5 pieces of chalk, and then k = 0. Student 0 doesn't have enough chalk, so he needs to replenish it.Copy the code
Example 2:
Input: chalk = [3,4,1,2], k = 25 Output: 1 explanation: students consume chalk as follows: - the student numbered 0 uses 3 pieces of chalk, then k = 22. - Student number 1 uses 4 pieces of chalk, and then k = 18. - Student number 2 uses 1 piece of chalk, and then k = 17. - Student number 3 uses 2 pieces of chalk and then k = 15. - Student 0 uses 3 pieces of chalk, then k = 12. - Student 1 uses 4 pieces of chalk, and then k = 8. - Student 2 uses 1 piece of chalk, and then k = 7. - Student number 3 uses 2 pieces of chalk, and then k = 5. - Student 0 uses 3 pieces of chalk and k = 2. Student 1 doesn't have enough chalk, so he needs to replenish it.Copy the code
2. Answer
- So let’s figure out how many pieces of chalk we have to consume in a round
- right
k
I take the modulus, I getk
It’s the amount of chalk left after a number of rounds - If I go through the students again, someone is going to run out of chalk
const chalkReplacer = (chalk, k) = > {
const sum = chalk.reduce((a, b) = > a + b);
k %= sum;
const len = chalk.length;
let sumNew = 0;
for (let i = 0; i < len; i++) {
sumNew += chalk[i];
if (sumNew > k) returni; }};Copy the code
😄 has recently created an open source repository to summarize LeetCode’s daily problems. It is currently available in C++ and JavaScript, and you are welcome to provide other language versions!
🖥️ Warehouse address: “One of the Day series”