leetcode-747-easy

Largest Number At Least Twice of Others

You are given an integer array nums where the largest integer is unique.

Determine 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, or return -1 otherwise.

Example 1:

Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
Example 2:

Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.
Constraints:

2 <= nums.length <= 50
0 <= nums[i] <= 100
The largest element in nums is unique.

思路一:分两步,第一步先找最大的数字,第二步遍历比较

    public int dominantIndex(int[] nums) {
        int max = -1;
        int ans = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > max) {
                max = nums[i];
                ans = i;
            }
        }

        for (int num : nums) {
            if (num != max && max < num * 2) {
                return -1;
            }
        }

        return ans;
    }

思路二:看了一下官方题解,发现更好的思路,只要找到第二大的数字,和最大的数字比较就行

posted @ 2023-02-15 21:25  iyiluo  阅读(15)  评论(0)    收藏  举报