Largest number at least twice of others
July 31, 2022
array-and-hashmapProblem URL: Largest number at least twice of others
We will keep track of both largest and second largest number while iterating through the whole nums array. Then if the largest number is at least twice as big as the second largest, then we return the index of largest number, else we return -1.
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
largest, second = -1, -1
for num in nums:
if num >= largest:
second = largest
largest = num
elif num >= second:
second = num
return nums.index(largest) if largest >= second*2 else -1
Time Complexity: O(n)
Space Complexity: O(1)