当前位置: 代码迷 >> 综合 >> leetcode 747. 至少是其他数字两倍的最大数
  详细解决方案

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

热度:23   发布时间:2024-03-09 11:39:38.0

在看题目的示例2时,给了我启发,要想一个数是其他所有数的2倍以上,那它只需要是第2大的数两倍以上。所以就变成了遍历一遍数组,找出其中的最大数和第2大的数,然后比较是不是2倍。

用时0ms

class Solution {
public:int dominantIndex(vector<int>& nums) {if(nums.size() == 1)return 0;int max1 = INT_MIN;int max2 = INT_MIN;int index = 0;for(int i = 0; i< nums.size(); ++i){if(nums[i] > max1){max2 = max1;max1 = nums[i];index = i;}else if(nums[i] > max2){max2 = nums[i];}}if(max1 >= 2*max2)return index;return -1;}
};