LeetCode 747. Largest Number At Least Twice of Others(至少是其他数字两倍的最大数) -- C语言

747. Largest Number At Least Twice of Others

In a given integer array nums, there is always exactly one largest element.

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

Example 1:

Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6 is the largest integer, and for every other number in the array x,
6 is more than 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 isn't at least as big as twice the value of 3, so we return -1.

Note:

  1. nums will have a length in the range [1, 50].
  2. Every nums[i] will be an integer in the range [0, 99].

解题思路:

遍历数组,找出第一大和第二大的元素,之后进行比较,符合条件则返回最大数下标,否则返回-1

/*
执行用时 : 0 ms, 在Largest Number At Least Twice of Others的C提交中击败了100.00% 的用户
内存消耗 : 7.1 MB, 在Largest Number At Least Twice of Others的C提交中击败了79.49% 的用户
*/

int dominantIndex(int* nums, int numsSize){
    //由题目可知最大值总是存在,即数组元素个数>0,所以对numsSize=0的情况可以不用考虑
    //由测试用例可知:只有一个元素时满足题设条件
    if(numsSize==1){
        return 0;
    }
    //记录最大的初始指向第一个元素
    int firstmax=nums[0];
    
    int k=0;//记录最大的下标
    
    //记录第二大的,题中给出数组值的范围在0~99,所以初始值设置为-1(其他<0的数亦可)。
    int secondmax=-1;
    
    int i;
    for(i=1;i<numsSize;i++){
        
        if(nums[i]>firstmax){
            
            //当前元素最大,则firstmax成为第二大。需维护三个变量
            secondmax=firstmax;
            firstmax=nums[i];
            k=i;
        }
        else if(nums[i]>secondmax){
            
            //如果当前元素是第二大,则该变记录的第二大
            secondmax = nums[i];
        }//if
        
    }//for
    
    if(firstmax >= secondmax*2){
        return k;
    }
    else{
        return -1;
    }
}

后记:

需注意当前元素不是最大时有可能是第二大,所以需要再比较确定是否是第二大。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值