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

时间:2020-05-20 11:58:53   收藏:0   阅读:46

题目:

技术图片

 

 

解答:

思路:

一次遍历找到最大的数max1和第二大的数max2,然后看看最大的数是不是大于等于第二大的数的两倍。如果是的话那么肯定满足最大数max1大于等于数组中其他数组的两倍了。

 1 class Solution {
 2 public:
 3     int dominantIndex(vector<int>& nums) 
 4     {
 5         int max1 = -1;
 6         int max2 = -1;
 7         int maxIndex = 0;
 8         
 9         for(int i = 0; i < nums.size(); i++)
10         {
11             if(nums[i] > max1)
12             {
13                 max2 = max1;
14                 max1 = nums[i];
15                 maxIndex = i;
16             }
17             else if(nums[i] > max2)
18             {
19                 max2 = nums[i];
20             }
21         }
22         
23         return max1 >= 2 * max2 ? maxIndex : -1;
24     }
25 };

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!