我正在努力解决最大数至少是其他数的两倍 - LeetCode
- 最大的数量至少是其他人的两倍
在给定的整数数组
nums中,总是有一个最大的元素。找出数组中最大的元素是否至少是数组中其他数字的两倍。
如果是,则返回最大元素的索引,否则返回-1。
示例 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.示例 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.笔记:
nums将有一个范围内的长度[1, 50]。- Every
nums[i]将是范围内的整数[0, 99]。
条件nums将有一个范围内的长度,[1, 50]不需要检查len(nums) ==1和nums == None
我的解决方案
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
"""
#solution 1
#1S#############
G:List[int],
F:index
RQ: largest and at least twice the second
#2S#############
CP:
RU: largetst >= second * 2
#3S##############
"""
#base case
if len(nums) == 1: return -1
lookup = {nums[i]:i for i in range(len(nums))}
nums.sort()
first = nums[-1]
second = nums[-2]
if first >= second * 2:
return lookup[first]
else:
return -1 #failure
#4C########################
# nums = [1] output = 0
运行测试用例:
nums = [1]
my output is : -1 #do not exist such a laregest number
#but the expected is
0
怎么能理解这个Testcase?
我的理解是,如果只有一个元素,没有其他元素,其他元素都没有,所以条件:
找出数组中最大的元素是否至少是数组中其他数字的两倍。
不满意。