leetcode (Largest Number At Least Twice of Others)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/84728236

Title:Largest Number At Least Twice of Others   747

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/largest-number-at-least-twice-of-others/

1. 找到最大值并记录其下标,找到第二大值

时间复杂度:O(n),两次一层for循环,需要遍历整个数组。

空间复杂度:O(1),没有申请额外的空间。

    /**
     * 找到最大值并记录其下标,找到第二大值,然后最大值除以第二大值来判断,需要注意:1、数组只有一个数,2、第二大值为0
     * @param nums
     * @return
     */
    public static int dominantIndex(int[] nums) {

        if (nums == null || nums.length <= 0) {
            return -1;
        }

        if (nums.length == 1) {
            return 0;
        }

        int firstMax = Integer.MIN_VALUE;
        int secondMax = Integer.MIN_VALUE;
        int index = -1;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > firstMax) {
                firstMax = nums[i];
                index = i;
            }
        }

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > secondMax && nums[i] < firstMax) {
                secondMax = nums[i];
            }
        }

        if (secondMax == 0) {
            return index;
        }

        if (firstMax / secondMax >= 2) {
            return index;
        }
        else {
            return -1;
        }

    }

2.  直接找到最大值的下标,然后比较最大值与其余数乘以2

时间复杂度:O(n),两次一层for循环,需要遍历整个数组。

空间复杂度:O(1),没有申请额外的空间。

    /**
     * 直接找到最大值的下标,然后比较最大值与其余数乘以2
     * @param nums
     * @return
     */
    public static int dominantIndex1(int[] nums) {

        if (nums == null || nums.length <= 0) {
            return -1;
        }

        int maxIndex = 0;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > nums[maxIndex]) {
                maxIndex = i;
            }
        }

        for (int i = 0; i < nums.length; i++) {
            if (i != maxIndex && nums[maxIndex] < nums[i] * 2) {
                return -1;
            }
        }

        return maxIndex;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/84728236
今日推荐