leetcode747

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.

class Solution {
public:
    int dominantIndex(vector<int>& nums) {
         vector<int> num1(nums);
        int i = num1.size();
        int t = i;
       sort(num1.begin(),num1.end(),less<int>());
       while(num1[i-1] == num1[i-2])
           i--;
       if(num1[t-1]-num1[i-2]>=num1[i-2])
           {
               return distance(nums.begin(),max_element(nums.begin(),nums.end()));
                
           }
        else 
            return -1;
    }
};

里面运用相关知识:
①对vector的sort排序:sort(v.begin(),v.end(),less<int>());  (升序)

降序则将最后参数的 less<int>()改成greater<int>()

②求vector内最大元素的位置

max_element(v.begin(),v.end())可得最大值的迭代器,类似指针但是又不是指针,它的相对位置需要通过和首位置相比才可得出。

③求最大元素位置所在的下标(类似数组中元素的位置)

distance(v.begin(),max_element(...))

猜你喜欢

转载自blog.csdn.net/qq_35601980/article/details/85334121