Question:
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.
Example:
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.
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.
Solution:
/**
* @param {number[]} nums
* @return {number}
*/
var dominantIndex = function(nums) {
if (nums.length < 2)return 0;
//无耻的用js特性解决。。。
//只需要比较最大的值和第二大的值
let arr = [].concat(nums).sort((a,b)=>b-a);
return arr[0]>=arr[1]*2 ? nums.indexOf(arr[0]) : -1;
};
Runtime: 72 ms, faster than 19.20% of JavaScript online submissions for Largest Number At Least Twice of Others.
/**
* @param {number[]} nums
* @return {number}
*/
var dominantIndex = function(nums) {
if (nums.length < 2)return 0;
let max = 0;
// 使用选择排序,只需要找出前2个极值
for(let i=0; i<2; i++){
let _max = i
for(let j=i+1; j<nums.length; j++){
if(nums[_max]<nums[j]){
_max=j;
i===0 && (max=j)
}
}
//交换
if(i!==_max){
let temp = nums[i];
nums[i] = nums[_max];
nums[_max] = temp;
}
}
return nums[0]>=nums[1]*2 ? max : -1;
};
Runtime: 56 ms, faster than 98.91% of JavaScript online submissions for Largest Number At Least Twice of Others.