【LeetCode】力扣刷题之路 (20240715~20240719)

题目(20240715~20240719)

3074.重新分装苹果

给你一个长度为 n 的数组 apple 和另一个长度为 m 的数组 capacity。
一共有 n 个包裹,其中第 i 个包裹中装着 apple[i] 个苹果。同时,还有 m 个箱子,第 i 个箱子的容量为 capacity[i] 个苹果。
请你选择一些箱子来将这 n 个包裹中的苹果重新分装到箱子中,返回你需要选择的箱子的最小数量。
注意,同一个包裹中的苹果可以分装到不同的箱子中。

示例 1

输入:apple = [1,3,2], capacity = [4,3,1,5,2]
输出:2
解释:使用容量为 4 和 5 的箱子。
总容量大于或等于苹果的总数,所以可以完成重新分装。

示例 2

输入:apple = [5,5,5], capacity = [2,4,2,7]
输出:4
解释:需要使用所有箱子。

提示

  • 1 <= n == apple.length <= 50
  • 1 <= m == capacity.length <= 50
  • 1 <= apple[i], capacity[i] <= 50
  • 输入数据保证可以将包裹中的苹果重新分装到箱子中。

代码

from typing import List


class Solution:
    def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int:
        # 贪心算法
        sa = sum(apple)  # 苹果总数
        capacity.sort(reverse=True)  # 箱子容量倒序排列
        for i, c in enumerate(capacity, 1):
            if sa > c:
                sa -= c
                continue
            if sa <= c:
                return i


if __name__ == '__main__':
    s = Solution()
    # 3074.重新分装苹果 - 示例1
    apple = [1, 3, 2]
    capacity = [4, 3, 1, 5, 2]
    res = s.minimumBoxes(apple, capacity)
    print(res)  # 输出:2
    # 示例2
    apple = [5, 5, 5]
    capacity = [2, 4, 2, 7]
    res = s.minimumBoxes(apple, capacity)
    print(res)  # 输出:4
    

面试题 10.11. 峰与谷

在一个整数数组中,“峰”是大于或等于相邻整数的元素,相应地,“谷”是小于或等于相邻整数的元素。例如,在数组{5, 8, 4, 2, 3, 4, 6}中,{8, 6}是峰, {5, 2}是谷。现在给定一个整数数组,将该数组按峰与谷的交替顺序排序。

示例

输入: [5, 3, 1, 2, 3]
输出: [5, 1, 3, 2, 3]

提示

  • nums.length <= 10000

代码

from typing import List


class Solution:
    def wiggleSort(self, nums: List[int]) -> None:
        for i in range(len(nums) - 1):
            if i % 2 == 0:
                if nums[i] < nums[i+1]:
                    nums[i], nums[i+1] = nums[i+1], nums[i]
            else:
                if nums[i] > nums[i+1]:
                    nums[i], nums[i+1] = nums[i+1], nums[i]


if __name__ == '__main__':
    s = Solution()
    # 面试题 10.11. 峰与谷 - 示例1
    nums = [5, 3, 1, 2, 3]
    s.wiggleSort(nums)
    print(nums)  # 输出:[5, 1, 3, 2, 3]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值