C++ Solution - Easy to Understand


  • 5
    int search(vector<int> &nums,int A)
    {
        int i=0;
        for(i=0;i<nums.size();i++)
            if(nums[i] == A)
                break;
        
        if(i == nums.size() || i == nums.size()-1)
            return -1;
        
        for(;i<nums.size();i++)
            if(nums[i] > A)
                return nums[i];
        
        return -1;
    }
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        
        vector<int> ans(findNums.size());
        for(int i=0;i<findNums.size();i++)
        {
            ans[i] = search(nums,findNums[i]);
        }
        return ans;
    }

  • 2
    W

    Thanks! I rewote the search() based on your idea.
    '''
    int search(vector<int>& nums,int target)
    {
    int i = 0;
    for(;i<nums.size();i++)
    {
    if (nums[i]==target) break;
    }
    i++;
    for(;i<nums.size();i++)
    {
    if (nums[i]>target) return nums[i];
    }
    return -1;
    }
    '''


  • 0
    M

    O(n2) soln. not very helpful.


  • 0
    A

    @mayankr1990 its O(mn) t


Log in to reply
 

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