747. Largest Number At Least Twice of Others

In a given integer array nums, 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 the index of 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

 

posted @ 2020-07-14 21:58  whatyouthink  阅读(100)  评论(0编辑  收藏  举报