在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ We distribute some number of We then give 1 candy to the first person, 2 candies to the second person, and so on until we give Then, we go back to the start of the row, giving This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift). Return an array (of length Example 1: Input: candies = 7, num_people = 4 Output: [1,2,3,1] Explanation: On the first turn, ans[0] += 1, and the array is [1,0,0,0]. On the second turn, ans[1] += 2, and the array is [1,2,0,0]. On the third turn, ans[2] += 3, and the array is [1,2,3,0]. On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1]. Example 2: Input: candies = 10, num_people = 3 Output: [5,2,3] Explanation: On the first turn, ans[0] += 1, and the array is [1,0,0]. On the second turn, ans[1] += 2, and the array is [1,2,0]. On the third turn, ans[2] += 3, and the array is [1,2,3]. On the fourth turn, ans[0] += 4, and the final array is [5,2,3]. Constraints:
排排坐,分糖果。 我们买了一些糖果 给第一个小朋友 1 颗糖果,第二个小朋友 2 颗,依此类推,直到给最后一个小朋友 然后,我们再回到队伍的起点,给第一个小朋友 重复上述过程(每次都比上一次多给出一颗糖果,当到达队伍终点后再次从队伍起点开始),直到我们分完所有的糖果。注意,就算我们手中的剩下糖果数不够(不比前一次发出的糖果多),这些糖果也会全部发给当前的小朋友。 返回一个长度为 示例 1: 输入:candies = 7, num_people = 4 输出:[1,2,3,1] 解释: 第一次,ans[0] += 1,数组变为 [1,0,0,0]。 第二次,ans[1] += 2,数组变为 [1,2,0,0]。 第三次,ans[2] += 3,数组变为 [1,2,3,0]。 第四次,ans[3] += 1(因为此时只剩下 1 颗糖果),最终数组变为 [1,2,3,1]。 示例 2: 输入:candies = 10, num_people = 3 输出:[5,2,3] 解释: 第一次,ans[0] += 1,数组变为 [1,0,0]。 第二次,ans[1] += 2,数组变为 [1,2,0]。 第三次,ans[2] += 3,数组变为 [1,2,3]。 第四次,ans[0] += 4,最终数组变为 [5,2,3]。 提示:
4ms
1 class Solution { 2 func distributeCandies(_ candies: Int, _ num_people: Int) -> [Int] { 3 var distribution = Array(repeating: 0, count: num_people) 4 5 var step = 0 6 var remaining = candies 7 while 0 < remaining { 8 let index = step % distribution.count 9 let amount = min(step + 1, remaining) 10 distribution[index] += amount 11 remaining -= amount 12 step += 1 13 } 14 return distribution 15 } 16 } Runtime: 8 ms Memory Usage: 20.9 MB
1 class Solution { 2 func distributeCandies(_ candies: Int, _ num_people: Int) -> [Int] { 3 var candies = candies 4 var a:[Int] = [Int](repeating:0,count:num_people) 5 var p:Int = 0 6 while(candies > 0) 7 { 8 let x:Int = min(candies, p + 1) 9 a[p % num_people] += x 10 candies -= x 11 p += 1 12 } 13 return a 14 } 15 }
|
请发表评论