747. 至少是其他数字两倍的最大数
查看原题

解题思路
先求出最大值,在求出次大值两者进行比较看是否满足大于等于2倍的关系。
- 先使用Math.max方法求出最大值,用indexOf()求出下标
- 将数组中的最大值删除
- 再次使用Math.max()求出最大值,此时是原数组的次大值
- 再比较两次求出的最大值,判断返回内容
代码
/**
* @param {number[]} nums
* @return {number}
*/
var dominantIndex = function(nums) {
const max = Math.max(...nums);
const index = nums.indexOf(max);
nums.splice(index,1);
const secondMax = Math.max(...nums);
if(max >= 2 * secondMax){
return index;
}
return -1;
};


浙公网安备 33010602011771号