[Leetcode] 747。他の番号の少なくとも2倍である最大の番号



747 Largest Number That Is Least Twice Other Number



タイトル説明:

与えられた配列nums Inには、常に最大の要素があります。



配列内の最大の要素が、配列内の他のすべての数値の少なくとも2倍の大きさであるかどうかを調べます。

そうである場合は、最大の要素のインデックスを返します。そうでない場合は、-1を返します。



例1:

nums

例2:

[1, 50]

促す:



  1. nums[i]長さの範囲は[0, 99]です。
  2. class Solution { public int dominantIndex(int[] nums) { int max1 = -1 int max2 = -1 int maxIndex = 0 for(int i=0i max1){ max2 = max1 max1 = nums[i] maxIndex = i }else if(nums[i] > max2){ max2 = nums[i] } } return max1>=2*max2?maxIndex:-1 } }整数範囲は
    enter: nums = [3, 6, 1, 0] Output: 1 Explanation: 6 is the largest integer, for other integers in the array, 6 is greater than twice the other elements in the array. The index of 6 is 1, so we return 1. 
    です。

問題解決のアイデア:

私の考えはもっと賢いです。これは前の414と同じ方法です。最大数を見つけ、1回トラバースして最大数max1と2番目に大きい数max2を見つけ、最大数が2番目に大きい数以上かどうかを確認します。の場合、最大数max1は、配列内の他の配列の数の2倍以上である必要があります。

コード(Java言語):

enter: nums = [1, 2, 3, 4] Output: -1 Explanation: 4 is not more than twice as large as 3, so we return -1.