python - 找出数组中最大的元素是否至少是数组中其他数字的两倍?
问题描述
我正在尝试运行一个程序来查找至少比数组中所有其他数字大两倍的数字的索引。
这是我的代码
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]
解决方案
这会检查许多可能的输入问题。
然后它对列表进行排序以获得您正在寻找的答案。为简单起见,我决定进行排序,但您也可以使用其他方法。我添加了评论,所以一切都很清楚,特别是关于输入测试,如被问及。
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
推荐阅读
- java - Java 扫描仪的工作原理
- php - Blade Laravel 中的未定义变量
- sql - 如何选择一些具有空行或空行的列
- r - DT 根据单独的数据框将背景颜色应用于单元格
- git - 构建失败并出现错误:无法锁定 ref 'refs/remotes/origin/users/bill.roper/develop':位于 b10165 但预期为 5f
- flutter - 除非使用 Center 包装小部件,否则 Flutter 设置容器小部件的宽度和高度不起作用?为什么?
- javascript - 使用 Bootstrap 3.3 更改打印行顺序
- postgresql - 具有多列索引的 postgres 查询的执行时间很慢
- javascript - 嵌入表单并将其发布到另一个站点
- django - AttributeError:模块“django.db.models”没有属性“级联”