LC 747


Solution to LeetCode 747 Largest Number At Least Twice of Others.

LeetCode 747

Largest Number At Least Twice of Others (Easy). [link]

One pointer p1 stores the largest value, the other pointer p2 stores the second largest value. The index is the index of the largest value. If the largest value is more than twice or twice larger than the second largest value, then the largest value must be more than twice or twice larger than all other values.

Time complexity O(N). Space complexity O(1).

class Solution(object):
    def dominantIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        p1, p2, index = -1, -1, 0
        for i, num in enumerate(nums):
            if num > p1: 
                p1, p2, index = num, p1, i
            elif num > p2:
                p2 = num
        return index if p1 >= p2 * 2 else -1

  TOC