1. 程式人生 > 實用技巧 >747. Largest Number At Least Twice of Others

747. Largest Number At Least Twice of Others

In a given integer arraynums, there is always exactly one largest element.

Find whether the largest element in the array is at least twice as much as every other number in the array.

If it is, return theindexof the largest element, otherwise return -1.

給一個數組,求最大值,如果最大值大於等於其他元素的兩倍,那麼就返回這個數的index,否則返回-1

其實就是求最大值和次大值,看看最大值是不是大於等於次大值的兩倍

class Solution(object):
    def dominantIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        index = -1
        first_max = 0
        second_max = 0
        for i in range(len(nums)):
            if nums[i] > first_max:
                second_max 
= first_max first_max = nums[i] index = i elif nums[i] > second_max: second_max = nums[i] if first_max >= second_max * 2: return index else: return -1