Skip to content

LeetCode 1744: 你能在你最喜欢的那天吃到你最喜欢的糖果吗?

Published: at 05:34 PMSuggest Changes

题目

你能在你最喜欢的那天吃到你最喜欢的糖果吗?

题解

官方题解

var canEat = function (candiesCount, queries) {
  const n = candiesCount.length;

  // 前缀和
  const sum = new Array(n).fill(0);
  sum[0] = candiesCount[0];
  for (let i = 1; i < n; ++i) {
    sum[i] = sum[i - 1] + candiesCount[i];
  }

  const q = queries.length;
  const ans = new Array(q).fill(0);
  for (let i = 0; i < q; ++i) {
    const query = queries[i];
    const favoriteType = query[0],
      favoriteDay = query[1],
      dailyCap = query[2];

    const x1 = favoriteDay + 1;
    const y1 = (favoriteDay + 1) * dailyCap;
    const x2 = favoriteType == 0 ? 1 : sum[favoriteType - 1] + 1;
    const y2 = sum[favoriteType];

    ans[i] = !(x1 > y2 || y1 < x2);
  }
  return ans;
};

let candiesCount = [7, 4, 5, 3, 8],
  queries = [
    [0, 2, 2],
    [4, 2, 4],
    [2, 13, 1000000000],
  ];

console.log('canEat :>> ', canEat(candiesCount, queries));

收获

JS 的技巧

const ans = new Array(q).fill(0);

输出长度为 q 的数组,用 0 填充

了解了前缀和这个东西

[7, 4, 5, 3, 8]

用前缀和得到

[7,7+4 7+4+5,7+4+5+3,7+4+5+3+8]

然后拿到区间进行判断。


Previous Post
JavaScript Array.prototype.flat() 兼容性处理
Next Post
LeetCode 523 连续的子数组和