[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)