Original link: leetcode-cn.com/problems/as…

Answer:

  1. The child will always be in a waiting state, and there may be more than one biscuit that will not satisfy the child’s appetite.
  2. For example, a child’s appetite is5Cookies for[6]Then you have to go through the cookie from 1 to 5 times to find the one that can be eaten.
  3. So you can iterate over cookies with a for loop, using a pointer as an index to iterate over the kids, and when you encounter a cookie that can be eaten, you increase the pointer by 1, and so does the number of kids being fed cookies.
  4. Since the pointer used to traverse the child and the number of children available for feeding cookies are always equal, the same variable can be used to represent them.
  5. It may be the case that the child has gone through all of the cookies and there are still cookies left, so you need to consider exiting the for loop early.
/ * * *@param {number[]} g
 * @param {number[]} s
 * @return {number}* /
var findContentChildren = function(g, s) {
  // Count the number of children who eat cookies. Since this value is equal to the index traversing g, use count to traverse g
  let count = 0;
  // sort g and s in order to ensure that there is no omission
  g.sort((a, b) = > a - b);
  s.sort((a, b) = > a - b);

  // Walk through each cookie to find the child who can eat it
  for (const cookie of s) {
    // If the current biscuit >= child's appetite, it can be eaten
    if (cookie >= g[count]) {
      // Increments count by 1, completing the count and enumeration of the next child to be matched
      count++;
      // If there are no children, but cookies still exist, exit the loop early
      if (count === g.length) {
        break; }}}return count;
};
Copy the code