【python3】leetcode 747. Largest Number At Least Twice of Others(easy)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/84997364

747. Largest Number At Least Twice of Others(easy)

In a given integer array nums, there is always exactly one largest element.

Find whether the largest element in the array is at least twice as much as every other number in the array.

If it is, return the index of the largest element, otherwise return -1.

Example 1:

Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6 is the largest integer, and for every other number in the array x,
6 is more than twice as big as x.  The index of value 6 is 1, so we return 1.

Example 2:

Input: nums = [1, 2, 3, 4]
Output: -1
Explanation: 4 isn't at least as big as twice the value of 3, so we return -1.

1 straightforward and method(fast 

这个方法笨拙在我觉得语句都好累赘嘤嘤嘤。。找出第一大和第二大的数字比较一下是否大于等于2倍

注意如果nums只有一个数字 返回下标0

class Solution:
    def dominantIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 1:return 0
        maxnum = max(nums)
        index = nums.index(maxnum)
        nums.remove(maxnum)
        second = max(nums)
        return index if maxnum >= 2*second else -1

Runtime: 40 ms, faster than 97.23% of Python3 

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/84997364
今日推荐