leetcode 747 至少是其他数字两倍的最大数 python3

题目描述

在一个给定的数组nums中,总是存在一个最大元素 。

查找数组中的最大元素是否至少是数组中每个其他数字的两倍。

如果是,则返回最大元素的索引,否则返回-1。

思路

先确定最大值和它的下标,创建一个空列表tmp。遍历nums,如果item==max或者max>=2*item,入tmp。最后检查tmp的长度和nums的长度是否一致即可

代码

class Solution:
    def dominantIndex(self, nums: List[int]) -> int:
        nums_max = max(nums)
        ind = nums.index(nums_max)
        tmp = []
        for item in nums:
            if nums_max >= 2 * item or item == nums_max:
                tmp.append(item)
        if len(tmp) == len(nums) :
            return ind
        else:
            return -1

猜你喜欢

转载自www.cnblogs.com/hinsbugdeveloper/p/12526379.html