# 747. Largest Number At Least Twice of Others

其實只要找出最大跟第二大互相比較就知道了

leetcode

/*
Input: nums = [3,6,1,0]
Output: 1

Input: nums = [1,2,3,4]
Output: -1
*/

/**
 * @param {number[]} nums
 * @return {number}
 */
var dominantIndex = function(nums) {
    let maxValueIndex = 0
    let doubleNums = [];
    for(let i=0; i<nums.length; i++){
        doubleNums[i] = nums[i]*2;
        maxValueIndex = nums[maxValueIndex] > nums[i] ? maxValueIndex : i
    }
    
     for(let i=0; i<doubleNums.length; i++){
        if(i!== maxValueIndex && doubleNums[i] > nums[maxValueIndex]){
            return -1
        }
     }
    
    return maxValueIndex
    
};

怎樣可以寫更好

我本來是陣列所有 item*2 ,然後再逐一比較有沒有大於最大值但這樣要 for 兩次,其實可以找出最大跟第二大就好,若 second*2 > first 那就 return -1 ,一個 for 就可以搞定

/**
 * @param {number[]} nums
 * @return {number}
 */
var dominantIndex = function(nums) {
    let index = 0
    let first = nums[index]
    let second = -Infinity;
    
    for(let i=1; i< nums.length; i++){
        if(nums[i] > first){
            second = first
            first = nums[i]
            index = i
        } else if(nums[i] > second && nums[i] < first) {
            second = nums[i]
        }
    }
    return first >= second*2 ? index : -1
    
};

Last updated