题目原文
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.
题目解释
给定一个整数数组,它一定有一个最大值,看看这个最大值是否至少是其它值的2倍,如果不是返回-1,否则返回最大值对应的下标
我的代码
/**
* @param {number[]} nums
* @return {number}
*/
var dominantIndex = function(nums) {
var max = Math.max.apply(null,nums); //这里求最大值
for(var index = 0; index <= nums.length; index++)
{ // 这里要排除自己
if(max < nums[index] * 2 && max != nums[index]) return -1;
}
for(var index = 0; index <= nums.length; index++)
{
if(max == nums[index]) return index;
}
};