2017/11/21 Leetcode 日记

 496. Next Greater Element I

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

 

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        vector<int> tNums;
        for(int i = 0, sz = findNums.size(); i < sz; i++){
            bool finded = false;
            int index = 0;
            for(int j = findN(findNums[i], nums), nsz = nums.size(); j < nsz; j++){
                if(nums[j] > findNums[i]){
                    index = j;
                    break;
                }
            }
            if(index == 0) tNums.push_back(-1);
            else tNums.push_back(nums[index]);
        }
        return tNums;
    }
    // return index of nums[k] == num
    int findN(int num, vector<int>& nums){
        for(int i = 0, sz = nums.size(); i < sz; i++){
            if(nums[i] == num){
                return i;
            }
        }
        return -1;
    }
};
c++

相关文章: