Python - Easy to understand one-liner solution


  • 0
    C
    def dominantIndex(self, nums):
            return nums.index(max(nums)) if all(max(nums) >= num * 2 for num in nums if num != max(nums)) else -1
    

    Clearer version:

        def dominantIndex(self, nums):
             max_ele = max(nums)
             for num in nums:
                 if num != max_ele and max_ele < num * 2:
                    return -1
             return nums.index(max_ele)
    

  • 0
    M

    Maybe we can use filter()

            return -1 if any(filter(lambda x: x * 2 > max(nums) if x != max(nums) else False, nums)) else nums.index(max(nums))
    
    

  • 1

    @candy.tgz Your one-liner is O(N^2) time complexity. Not worth making the code quadratic just to save one line


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.