codetop4:数组中第K个最大元素

数组中第K个最大元素

给定整数数组 nums 和整数 k,请返回数组中第 **k** 个最大的元素。

请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

你必须设计并实现时间复杂度为 O(n) 的算法解决此问题。

示例 1:

输入: [3,2,1,5,6,4], k = 2
输出: 5

示例 2:

输入: [3,2,3,1,2,4,5,5,6], k = 4
输出: 4

思路

送分题

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        nums.sort(reverse=True)
        return nums[k-1]

这样写比我使用希尔排序或者快速排序时间都少,这个是什么操作?

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        def backtrac(nums):
            if not nums or len(nums)==1:
                return nums
            left=[x for x in nums if x<nums[0]]
            mid=[x for x in nums if x==nums[0]]
            right=[x for x in nums if x>nums[0]]
            return backtrac(left)+mid+backtrac(right)
        return backtrac(nums)[-k]

image-20240406092556582

上面是使用sort函数,下面是使用快速排序。

Share

13 Responses

  1. This service is perfect for boosting your local business’ visibility on the map in a specific location.

    We provide Google Maps listing management, optimization, and promotion services that cover everything needed to rank in the Google 3-Pack.

    More info:
    https://www.speed-seo.net/ranking-in-the-maps-means-sales/

    Thanks and Regards
    Mike Miln

    PS: Want a ONE-TIME comprehensive local plan that covers everything?
    https://www.speed-seo.net/product/local-seo-bundle/

  2. Hi there,

    I have reviewed your domain in MOZ and have observed that you may benefit from an increase in authority.

    Our solution guarantees you a high-quality domain authority score within a period of three months. This will increase your organic visibility and strengthen your website authority, thus making it stronger against Google updates.

    Check out our deals for more details.
    https://www.monkeydigital.co/domain-authority-plan/

    NEW: Ahrefs Domain Rating
    https://www.monkeydigital.co/ahrefs-seo/

    Thanks and regards
    Mike Hill

  3. Erectile dysfunction treatments available online from TruePills.
    Discreet, next day delivery and lowest price guarantee.

    Viagra is a well-known, branded and common erectile dysfunction (ED) treatment for men.
    It’s available through our Online TruePills service.

    Trial ED Pack consists of the following ED drugs:

    Viagra Active Ingredient: Sildenafil 100mg 5 pills
    Cialis 20mg 5 pills
    Levitra 20mg 5 pills

    https://cutt.ly/7wC5m1Id
    https://cosmeticshop.ru/bitrix/redirect.php?event1=click_to_call&event2=&event3=&goto=https://true-pill.top/
    https://98.staikudrik.com/index/d1?diff=0&utm_source=ogdd&utm_campaign=26607&utm_content=&utm_clickid=uskkokskw44sooos&aurl=http%3A%2F%2Ftrue-pill.top&pushMode=popup
    https://www.asee.org/login?returnurl=https://true-pill.top/
    https://mlog.club/redirect?url=https://true-pill.top/
    https://wiki.lvl1.org/index.php?title=%2Ftrue-pill.top&action=edit&printable=yes

    Diltaretard
    Lapenax
    Nifcal
    Trichomonacid
    Formigran
    Flogostil
    Odontogesic
    Orfiril
    Actoplus Met
    Ixime
    Ketobe
    Azitrolit
    Virtaz
    Amlodipine
    Feldegel
    Suprax
    Furanthril
    Litiomal
    Ketoderm
    Spiricort
    Megadox
    Lohist
    Memomax
    Cardival
    Hytis
    Metoprim
    Mycoseb
    Nastil
    Norizec
    Cilostazol
    Lodosyn
    Fibrocard
    Fisiopred
    Soldesanil
    Serenil
    Assonax
    Cotrimstada
    Levetiracetamum
    Amadin
    Furacam

  4. Hi there,

    My name is Mike from Monkey Digital,

    Allow me to present to you a lifetime revenue opportunity of 35%
    That’s right, you can earn 35% of every order made by your affiliate for life.

    Simply register with us, generate your affiliate links, and incorporate them on your website, and you are done. It takes only 5 minutes to set up everything, and the payouts are sent each month.

    Click here to enroll with us today:
    https://www.monkeydigital.org/affiliate-dashboard/

    Think about it,
    Every website owner requires the use of search engine optimization (SEO) for their website. This endeavor holds significant potential for both parties involved.

    Thanks and regards
    Mike James

    Monkey Digital

  5. Erectile dysfunction treatments available online from TruePills.
    Discreet, next day delivery and lowest price guarantee.

    Viagra is a well-known, branded and common erectile dysfunction (ED) treatment for men.
    It’s available through our Online TruePills service.

    Trial ED Pack consists of the following ED drugs:

    Viagra Active Ingredient: Sildenafil 100mg 5 pills
    Cialis 20mg 5 pills
    Levitra 20mg 5 pills

    https://cutt.ly/dw7ChH4s
    https://ofisnye-kresla-shop.ru/bitrix/redirect.php?goto=https://true-pill.top/
    http://xn--90aeea2bghkbmep4j.xn--p1ai/bitrix/redirect.php?event1=&event2=&event3=&goto=https://true-pill.top/
    http://m.ww.indibrand.co.kr/member/login.html?noMemberOrder=&returnUrl=http%3a%2f%2ftrue-pill.top
    https://rutector.ru/bitrix/redirect.php?goto=https://true-pill.top/
    https://www.funeralunion.org/delete-company?nid=39&element=https://true-pill.top/

    Atornil
    Gabapentin
    Warin
    Florinefe
    Anadir
    Zinocep
    Maxeran
    Desal
    Neoceptin
    TamoxifГЁne
    Tesero
    Etan
    Raserdipina
    Dermatrans
    Doctinon
    Diuresix
    Octorax
    Fincar 5
    Xetinax
    Virpes
    Servamox
    Gordius
    Socosep
    Painoxam
    Doccefuro
    Agastin
    Clamoxyl
    Rapivir
    Nopres
    Opal
    Furoxim
    Endoxana
    Funga
    Siphene
    Bactrazol
    Vicclox
    Epimaz
    Vedatan
    Fodiss
    Genox

  6. Rybelsus – Quick and Easy Weight Lass

    According to randomised controlled trials, you start losing weight immediately after taking Rybelsus. After one month, the average weight loss on Rybelsus is around 2kg; after two months, it’s over 3kg.

    What does Rybelsus do to your body?

    Rybelsus (oral semaglutide) is a GLP-1 receptor agonist. It mimics a fullness hormone called GLP-1.

    Rybelsus reduces appetite and hunger by interacting with the brain’s appetite control centre, the hypothalamus. This effect on the brain helps you eat fewer calories and starts almost immediately after taking the pill.

    However, you might notice your hunger levels rising and falling in the first 4-5 weeks you take Rybelsus.

    It can take around 4-5 weeks for Rybelsus to reach a level in the body we call a steady state. A steady state is when the drug’s levels in the body remain consistent rather than spiking and falling.

    Interestingly, this initial weight loss is no different to other weight loss treatments or the impact of diet interventions on weight loss. The real effect of oral semaglutide is seen beyond three months.

    Oral semaglutide is a long-acting medication that’s started at a lower dose to reduce the number and severity of side effects as it’s built up to a higher maintenance dose.

    https://true-pill.top/rybelsus.html

  7. Профессиональные seo https://seo-optimizaciya-kazan.ru услуги для максимизации онлайн-видимости вашего бизнеса. Наши эксперты проведут глубокий анализ сайта, оптимизируют контент и структуру, улучшат технические аспекты и разработают индивидуальные стратегии продвижения.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Post comment

 ©2025 [忧郁小王子的乌托邦] - 稳定运行: