Easy C++ code with Time Complexity O(n) and Space Complexity O(1)


  • 0
    U

    class Solution {
    public:
    int dominantIndex(vector<int>& nums) {
    int mx=0,smx=0;
    int n=nums.size();
    nums.resize(n+1);
    nums.insert(nums.begin(),-1);
    for(int i=1;i<=n;i++){
    if(nums[i]>nums[mx]){
    smx=mx;
    mx=i;
    }else if(nums[i]>nums[smx]){
    smx=i;
    }
    }
    if(nums[mx]>=nums[smx]*2){
    return mx-1;
    }else{
    return -1;
    }
    }
    };


  • 0
    Z

    @uday28kumar same idea!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.