我本來是陣列所有 item*2 ,然後再逐一比較有沒有大於最大值但這樣要 for 兩次,其實可以找出最大跟第二大就好,若 second*2 > first 那就 return -1 ,一個 for 就可以搞定
/** * @param{number[]} nums * @return{number} */vardominantIndex=function(nums) {let index =0let 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 } elseif(nums[i] > second && nums[i] < first) { second = nums[i] } }return first >= second*2? index :-1};