至少是其他数字两倍的最大数

题目描述

给你一个整数数组 nums ,其中总是存在 唯一的 一个最大整数 。
请你找出数组中的最大元素并检查它是否 至少是数组中每个其他数字的两倍 。如果是,则返回 最大元素的下标 ,否则返回 -1

思路

找出最大数和第二大数看最大数是不是第二大数的两倍即可。

leetcode链接: 至少是其他数字两倍的最大数

代码:

int dominantIndex(int* nums, int numsSize){
    // 如果数组只有一个数 直接返回0下标
    if(numsSize == 1) {
        return 0;
    }
    
    int first_max_index = 0;
    int second_max_index = 0;
    /*
        要使用数组的第一个元素和第二个元素判断一下
        在赋值两个下标,否则会出现卡死的现象
    */
    if (nums[0] > nums[1]) {
        first_max_index = 0;
        second_max_index = 1;
    } else {
        first_max_index = 1;
        second_max_index = 0;
    }
    int i = 0;
    for (i = 2; i < numsSize; i++) {
        if (nums[i] > nums[first_max_index]) {
            second_max_index = first_max_index;
            first_max_index = i;
        } else if (nums[i] > nums[second_max_index]) {
            second_max_index = i;
        }
    }
    

    if (nums[first_max_index] >= 2 * nums[second_max_index]) {
        return first_max_index;
    } else {
        return -1;
    }

    
}
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值