[LeetCode] 747. Largest Number At Least Twice of Others

Posted codingEskimo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 747. Largest Number At Least Twice of Others相关的知识,希望对你有一定的参考价值。

这道题思路很简单,就是在一个loop下找最大的和第二大的数值。记住,python最小的数值是-sys.maxsize-1

class Solution:
    def dominantIndex(self, nums: List[int]) -> int:
        if not nums or len(nums) == 1:
            return 0
        
        largest, sec_largest, idx = -sys.maxsize - 1, -sys.maxsize - 1, 0
        
        for i in range(len(nums)):
            if nums[i] >= largest: 
                sec_largest = largest
                largest = nums[i]  
                idx = i
            if nums[i] > sec_largest and nums[i] < largest:
                sec_largest = nums[i]
        
        if largest >= 2 * sec_largest:
            return idx
        return -1
            

 

以上是关于[LeetCode] 747. Largest Number At Least Twice of Others的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-747-Largest Number At Least Twice of Others(求vector的最大值和次大值)

747. Largest Number At Least Twice of Others

747_Largest-Number-At-Least-Twice-of-Others

747.Largest Number At Least Twice of Others

747. Largest Number Greater Than Twice of Others

747. Largest Number At Least Twice of Others