Leetcode简单 乞丐问题 English beggars(JS)

本文解析了一个编程挑战,描述了一种算法任务,要求根据给定数值数组和乞丐数量,计算每个乞丐分得的总和。通过JavaScript实现,利用reduce和数组操作,演示了如何实现时间复杂度优化的解决方案。涉及内容包括数组处理、迭代器和队列概念在编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刷题系列

Born a misinterpretation of this kata, your task here is pretty simple: given an array of values and an amount of beggars, you are supposed to return an array with the sum of what each beggar brings home, assuming they all take regular turns, from the first to the last.

For example: [1,2,3,4,5] for 2 beggars will return a result of [9,6], as the first one takes [1,3,5], the second collects [2,4].

The same array with 3 beggars would have in turn have produced a better out come for the second beggar: [5,7,3], as they will respectively take [1,4], [2,5] and [3].

Also note that not all beggars have to take the same amount of “offers”, meaning that the length of the array is not necessarily a multiple of n; length can be even shorter, in which case the last beggars will of course take nothing (0).

Note: in case you don’t get why this kata is about English beggars, then you are not familiar on how religiously queues are taken in the kingdom 😉

Note 2: do not modify the input array.

解题过程:
很简单的一题,当然要想出时间复杂度优秀的解法对于我这样的菜鸟来说还是需要花点时间去思考的,这里使用了js的Array(n)来创建一个长度为n,默认元素为empty的数组,然后用Array.prototype.fill()来把所有元素初始化为0;接下来是关键一步:先定义一个reducer,然后使用reduce() 方法对数组中的每个元素执行reducer函数,将其结果汇总为单个返回值。
reducer 函数接收4个参数:

  1. Accumulator (acc) (累计器)
  2. Current Value (cur) (当前值)
  3. Current Index(idx) (当前索引)
  4. Source Array (src) (源数组)
function beggars(values, n){
  //your code here
  var sums = Array(n).fill(0);
  const reducer = (array, amount, index) => {
        array[index % array.length] += amount;
        return array;
    };
  return values.reduce(reducer,sums);
}

题目链接: English beggars.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值