LeetCode 747. at least is the maximum number of other digital (Java) twice

747. at least twice the maximum number of other digital

In a given array nums in, there is always a maximum element.
Find an array of whether the largest element in the array is at least twice every other number.
If so, the index of the largest element is returned, otherwise -1.

Example 1:
Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6 is the greatest integer, for other integer array,
6 times larger than the other elements in the array. 6 index is 1, so we returned.

Tip:
the nums a length in the range [1, 50].
Each nums [i] is an integer in the range [0, 100].

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/largest-number-at-least-twice-of-others
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Ideas : the maximum value and the second largest two variables were recorded, and finally only the second largest value is greater than twice the maximum can be verified

class Solution {
    public int dominantIndex(int[] nums) {
        int max=nums[0];
        int second=-1;
        int index=0;
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i]>max)//如果当前值大于最大值
            {
                second=max;
                max=nums[i];
                index=i;
            }
            else if(nums[i]>second&&nums[i]<max)//如果当前值大于第二大值小于最大值
            {
                second=nums[i];
            }
        }
        if(max>=second*2)
        {
            return index;
        }
        else
        {
            return -1;
        }
    }
}
Published 88 original articles · won praise 0 · Views 2155

Guess you like

Origin blog.csdn.net/nuts_and_bolts/article/details/105096638