leetCode刷题记录之747Largest Number At Least Twice of Others

题目原文

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;
    } 
};
发布了135 篇原创文章 · 获赞 10 · 访问量 6239

猜你喜欢

转载自blog.csdn.net/gunsmoke/article/details/104052585
今日推荐