贪心算法(三) ---cmp_to_key, 力扣452,力扣179

目录

cmp_to_key

比较函数

键函数

cmp_to_key 的作用

使用 cmp_to_key

代码解释

力扣452 ---射气球

题目 

分析 

 代码

力扣179 ---最大数

题目

分析

代码 


 

cmp_to_key

在Python中,cmp_to_key 是一个函数,它将一个比较函数转换成一个键函数,使得比较函数可以用作排序算法的键。这个函数在Python 3中通过functools模块提供。

比较函数

在Python中,比较函数是一个接受两个参数并返回以下三种值之一的函数:

  • 负数:表示第一个参数小于第二个参数。
  • 零:表示两个参数相等。
  • 正数:表示第一个参数大于第二个参数。

键函数

键函数是一个接受一个元素并返回一个值的函数,这个返回的值将被用作排序的依据。在Python的sort()方法或sorted()函数中,可以提供一个键函数来决定排序的方式。

cmp_to_key 的作用

由于Python的sort()方法和sorted()函数需要键函数返回的是具体的比较结果(-1、0、1),而不是比较函数的返回值(负数、零、正数),因此cmp_to_key的作用就是将比较函数转换成一个符合要求的键函数。

使用 cmp_to_key

以下是如何使用cmp_to_key的一个例子:

python
from functools import cmp_to_key

def compare_strings(a, b):
    # 比较两个字符串
    return (a > b) - (a < b)

# 使用cmp_to_key将比较函数转换成键函数
sorted_strings = sorted(["banana", "apple", "cherry"], key=cmp_to_key(compare_strings))
print(sorted_strings)

在这个例子中:

  • compare_strings 是一个比较函数,它比较两个字符串a和b。
  • cmp_to_key(compare_strings) 将compare_strings转换成一个键函数,这个键函数可以用作sorted()函数的键。

代码解释

  1. compare_strings 函数返回1、0或-1,这与Python比较操作符的返回值一致。
  2. cmp_to_key(compare_strings) 将compare_strings转换为一个键函数。
  3. sorted() 函数使用这个键函数对字符串列表进行排序。

力扣452 ---射气球

 

有一些球形气球贴在一堵用 XY 平面表示的墙面上。墙面上的气球记录在整数数组 points ,其中points[i] = [xstart, xend] 表示水平直径在 xstart 和 xend之间的气球。你不知道气球的确切 y 坐标。

一支弓箭可以沿着 x 轴从不同点 完全垂直 地射出。在坐标 x 处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足  xstart ≤ x ≤ xend,则该气球会被 引爆 。可以射出的弓箭的数量 没有限制 。 弓箭一旦被射出之后,可以无限地前进。

给你一个数组 points ,返回引爆所有气球所必须射出的 最小 弓箭数 

示例 1:

输入:points = [[10,16],[2,8],[1,6],[7,12]]
输出:2
解释:气球可以用2支箭来爆破:
-在x = 6处射出箭,击破气球[2,8]和[1,6]。
-在x = 11处发射箭,击破气球[10,16]和[7,12]。

示例 2:

输入:points = [[1,2],[3,4],[5,6],[7,8]]
输出:4
解释:每个气球需要射出一支箭,总共需要4支箭。

示例 3:

输入:points = [[1,2],[2,3],[3,4],[4,5]]
输出:2
解释:气球可以用2支箭来爆破:
- 在x = 2处发射箭,击破气球[1,2]和[2,3]。
- 在x = 4处射出箭,击破气球[3,4]和[4,5]。

提示:

  • 1 <= points.length <= 105
  • points[i].length == 2
  • -231 <= xstart < xend <= 231 - 1

题目 

分析 

 代码

class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        if not points:
            return 0

        points.sort(key=lambda x: x[0])
        arrow = 1
        right = points[0][1]
        for i in range(0, len(points)):  # 修正了循环语法
            if right >= points[i][0]:  # 气球的开始时间小于等于当前箭的结束时间
                if right > points[i][1]:  # 更新箭的结束时间为当前气球的结束时间,如果它更小的话
                    right = points[i][1]
            else:
                arrow += 1
                right = points[i][1]  # 新箭的结束时间是当前气球的结束时间

        return arrow

力扣179 ---最大数

题目

给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。

注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。

示例 1:

输入:nums = [10,2]
输出:"210"

示例 2:

输入:nums = [3,30,34,5,9]
输出:"9534330"

提示:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 109

分析

代码 

 

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        def sort_rule(x, y):
            a, b = x + y, y + x
            if a < b: return 1
            elif a > b: return -1
            else: return 0
        
        strs = [str(num) for num in nums]
        strs.sort(key = cmp_to_key(sort_rule))
        if strs[0] == "0":
            return "0"
        return ''.join(strs)

  • 16
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
The `functools.cmp_to_key` function is a utility function in Python's `functools` module that helps convert a comparison function to a key function. In Python, sorting a list of objects requires a way to compare the objects. This is done by providing a comparison function that takes two objects as input and returns `-1`, `0`, or `1` depending on whether the first object is less than, equal to, or greater than the second object. However, some sorting functions in Python (such as the `sorted` function) require a key function instead of a comparison function. A key function takes a single object as input and returns a value that can be used for sorting. The `cmp_to_key` function helps convert a comparison function to a key function by returning a new function that takes a single object as input and returns a tuple `(comparison_result, object)` where `comparison_result` is the result of calling the original comparison function with the input object and another object, and `object` is the input object itself. This tuple can then be used for sorting. Here's an example of how to use `cmp_to_key`: ``` from functools import cmp_to_key def compare_length(str1, str2): if len(str1) < len(str2): return -1 elif len(str1) > len(str2): return 1 else: return 0 strings = ['cat', 'dog', 'elephant', 'a', 'zebra'] sorted_strings = sorted(strings, key=cmp_to_key(compare_length)) print(sorted_strings) # Output: ['a', 'cat', 'dog', 'zebra', 'elephant'] ``` In this example, we define a comparison function `compare_length` that compares the lengths of two strings. We then use `cmp_to_key` to convert this comparison function to a key function, and pass it to the `sorted` function to sort a list of strings by length. The resulting sorted list is `['a', 'cat', 'dog', 'zebra', 'elephant']`.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值