题目
747. Largest Number At Least Twice of Others
解题方法
遍历数组,维护最大值maxnum、次大值的两倍twice、最大值位置maxnumpos三个变量:若当前位置大于maxnum,则令twice为maxnum的两倍,更新maxnum和maxnumpos;否则,令twice = max(twice, nums[i] * 2),循环结束后判断maxnum和twice的关系即可。
时间复杂度:O(n)
空间复杂度:O(1)
代码
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
maxnum = nums[0]
twice = 0
maxnumpos = 0
for i in range(1, len(nums)):
if nums[i] > maxnum:
twice = maxnum * 2
maxnum = nums[i]
maxnumpos = i
else:
twice = max(twice, nums[i] * 2)
if maxnum >= twice:
return maxnumpos
else:
return -1