首页 > 解决方案 > 找出数组中最大的元素是否至少是数组中其他数字的两倍?

问题描述

我正在尝试运行一个程序来查找至少比数组中所有其他数字大两倍的数字的索引。

这是我的代码

def dominantIndex(self, nums):

        max_num = max(nums)
        max_i =nums.index(max_num)
        if len(nums) == 1:
           return nums.index(max_num)

        for num in nums:
            if max_num >= 2*num:
                return num.index(max_num)
            return -1

但是,它并不适用于所有输入。有人可以修复它并检查输入,例如:

[1,0]
[0,3,4,8]
[0,3,5,2]

标签: pythonarrayslist

解决方案


这会检查许多可能的输入问题。

然后它对列表进行排序以获得您正在寻找的答案。为简单起见,我决定进行排序,但您也可以使用其他方法。我添加了评论,所以一切都很清楚,特别是关于输入测试,如被问及。

def dominantIndex(nums):
    # If the array is empty or None or not a list, return -1
    if not nums or type(nums) != list:
        return -1
    # If the array is of length 1, return the only index, 0
    elif len(nums) == 1:
        return 0

    sorted_numbers = sorted(nums)
    # If the highest number is twice the second largest, return it's index
    if sorted_numbers[-2] * 2 <= sorted_numbers[-1]:
        return nums.index(sorted_numbers[-1])
    else:
        return -1

推荐阅读