747. Largest Number At Least Twice of Others

问题:

给定数组,若存在最大值是任意其他元素的2倍以上,则返回该最大值的index,否则返回-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:
nums will have a length in the range [1, 50].
Every nums[i] will be an integer in the range [0, 99].

  

解法:

设两个变量记录最大值largest和第二大值second

遍历数组,最后若第二大值*2<=最大值,那么返回largest的index

代码参考:

 1 class Solution {
 2 public:
 3     int dominantIndex(vector<int>& nums) {
 4         int res=-1, largest=0, second=0;
 5         for(int i=0; i<nums.size(); i++){
 6             if(nums[i]>largest){
 7                 second=largest;
 8                 largest=nums[i];
 9                 res=i;
10             }else if(nums[i]>second && nums[i] != largest){
11                 second=nums[i];
12             }
13         }
14         return second*2<=largest? res:-1;
15     }
16 };
原文地址:https://www.cnblogs.com/habibah-chang/p/12835844.html