1. 程式人生 > >至少是其他數字兩倍的最大數

至少是其他數字兩倍的最大數

 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:

nums will have a length in the range [1, 50].

Every nums[i] will be an integer in the range [0, 99]   

 

題意:找出陣列中的最大元素,判斷這個數是否至少是陣列中其它元素的兩倍,如果沒有這樣的元素,返回-1。                                           

思路:找到最大元素,儲存其下標,然後對陣列排序,找到第二大的數,兩個數作比較,如果最大的元素大於或者等於第二大元素的二倍,那麼肯定也就大於其餘元素的二倍,如果是小於的話,那就返回-1。

class Solution {
public:
    //找到最大數的id,然後排序和第二大的數比較,如果比它還大,那就返回最大數的id
    int dominantIndex(vector<int>& nums) {
        int len=nums.size();
        int max=0;
        int id=0;
        for(int i=0;i<len;i++){
            if(nums[i]>max){
                max=nums[i];
                id=i;
            }
        }
        sort(nums.begin(),nums.end());  //對vector進行排序
        if(max<nums[len-2]*2) id=-1;
        return id;    
    }
};