1. 程式人生 > >leetcode-747-Largest Number At Least Twice of Others(求vector的最大值和次大值)

leetcode-747-Largest Number At Least Twice of Others(求vector的最大值和次大值)

mis bmi 函數 ret num 容易 浪費 ever leetcode

題目描述:

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:

  1. nums will have a length in the range [1, 50].
  2. Every nums[i] will be an integer in the range [0, 99].

要完成的函數:

int dominantIndex(vector<int>& nums)

說明:

給定一個vector,要求判斷這個vector中的最大值是不是至少等於其他所有元素值的兩倍,如果是的話,返回最大值的位置,如果不是,返回-1。

這道題其實相當容易,就是求vector的最大值和次大值,以及在求最大值的過程中記錄一下最大值的位置。

我們考慮一下邊界條件,只有一個元素和只有兩個元素的情況,接著構造一般情況下的代碼,如下:

   int dominantIndex(vector<int>& nums) 
    {
        int s1=nums.size();
        if(s1==1)//只有一個元素的邊界條件
            return 0;
        else if(s1==2)//只有兩個元素的邊界條件
        {
            if(nums[0]>nums[1])
            {
                if(nums[0]>=2*nums[1])
                    return 0;
                else
                    return -1;
            }
            else
            {
                if(nums[1]>=2*nums[0])
                    return 1;
                else
                    return -1;
            }
        }
        int max1,max2,i=2,index;
        if(nums[0]>=nums[1])
        {
            max1=nums[0];
            max2=nums[1];
            index=0;
        }
        else
        {
            max1=nums[1];
            max2=nums[0];
            index=1;
        }
        while(i<s1)//i從2開始
        {
            if(nums[i]>=max1)
            {
                max2=max1;
                max1=nums[i];
                index=i;
            }
            else
            {
                if(nums[i]>=max2)
                    max2=nums[i];
            }
            i++;
        }
        if(max1>=2*max2)
            return index;
        else
            return -1;
    }

上述代碼雖然條件判斷語句多了點,但大體上來看沒有浪費很多時間,代碼也不難理解。

實測9ms,beats 81.63% of cpp submissions。

leetcode-747-Largest Number At Least Twice of Others(求vector的最大值和次大值)