题目描述
在一个给定的数组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