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.


给定一个数组,数组中有一个最大值,需要对比一下这个最大值是不是比其他的所有数字都大两倍,如果是的话则返回这个最大值的下标,不是的话则返回-1.

第一首先循环一遍数组,找到最大值和下标,然后再次遍历数组,对比最大值和其他值,如果发现最大值没有比其他值大两倍,就返回-1,否则最后返回最大值下标。

class Solution {
public:
    int dominantIndex(vector<int>& nums) {
        int maxNum=0;//最大数
        int maxIndex;//最大数的下标
        for(int i=0; i < nums.size(); i++) {
            if(nums[i] >= maxNum) {//记录最大值和下标
                maxNum = nums[i];
                maxIndex = i;
            }
        }

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

第二首先也是遍历一边数组找到最大值和下标,然后将原数组排序,排序之后的最后一位肯定就是最大值了,只需要对比一下最大值是否比倒数第二大,看看是不是大于两倍。

class Solution {
public:
    int dominantIndex(vector<int>& nums) {
        int maxNum=0;//最大数
        int maxIndex;//最大数的下标
        for(int i=0; i < nums.size(); i++) {
            if(nums[i] >= maxNum) {//记录最大值和下标
                maxNum = nums[i];
                maxIndex = i;
            }
        }
        sort(nums.begin(),nums.end());//排序
        if(maxNum < 2*nums[nums.size()-2]) {
            return -1;
        }
        return maxIndex;
    }
};

第三直接遍历一遍数组,分别找到最大值及其下标,同时也需要找到倒数第二大的值。然后同样的看看是不是大两倍。

class Solution {
public:
    int dominantIndex(vector<int>& nums) {
        int maxNum=-1;//最大数
        int maxIndex;//最大数的下标
        int lastMaxNum=-1;//上一个最大数
        for(int i=0; i < nums.size(); i++) {
            if(nums[i] >= lastMaxNum) {//先看一看当前的是否大于上一个最大值
                lastMaxNum = nums[i];//先让上一个最大值等于当前的
                if(nums[i] > maxNum) {//如果这个比最大值还大的话,更换当前最大值和上一个最大值
                    lastMaxNum = maxNum;
                    maxNum = nums[i];
                    maxIndex = i;
                }
            }
        }
        //cout << maxNum << "," << lastMaxNum << endl;
        if(maxNum < 2*lastMaxNum) {
            return -1;
        }
        return maxIndex;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值