题目:
在一个给定的数组nums
中,总是存在一个最大元素 。
查找数组中的最大元素是否至少是数组中每个其他数字的两倍。
如果是,则返回最大元素的索引,否则返回-1。
提示:
nums
的长度范围在[1, 50]
.- 每个
nums[i]
的整数范围在[0, 99]
好消息,我终于可以自己完成一题了,虽然有点偷鸡
class Solution: def dominantIndex(self, nums: List[int]) -> int: if(len(nums)==1): return 0 max1=0 max2=0 max1=max(nums) a=nums.index(max1) num=nums num.pop(a) max2=max(num) if(max1>=2*max2): return a return -1
执行用时 : 96 ms, 在Largest Number At Least Twice of Others的Python3提交中击败了7.30% 的用户
内存消耗 : 13.3 MB, 在Largest Number At Least Twice of Others的Python3提交中击败了12.06% 的用户
虽然很惨,但是还是很高兴哈哈哈哈
借鉴一下别人的
int dominantIndex(int* nums, int numsSize) { int max; int sec; int idx; int i; if(0 == numsSize){ return -1; } if(1 == numsSize){ return 0; } if(nums[0]>nums[1]){ max = nums[0]; sec = nums[1]; idx = 0; }else{ max = nums[1]; sec = nums[0]; idx = 1; } for(i=2; i<numsSize;i++){ if(nums[i]>max){ sec = max; max = nums[i]; idx = i; }else if(nums[i]>sec){ sec = nums[i]; } } return (max/2>=sec)?idx:-1; }
不得不说,c的效率还是高啊。。。