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.

給定兩個列表(元素不重複)nums1和nums2,其中nums1是nums2的子集。查找nums1中每個元素nums1[i]在nums中的下一個大的元素(位於nums1[i]在nums2中對應位置的右方)。如果存在,則返回下一個大的元素;如果不存在,返回-1.

Example 1:


Example 2:


實現一:

使用迭代器iterator,使用find()函數查找nums1中元素在nums2中的位置,並使用distance()函數返回位置,然後再返回位置的右邊查找下一個大的元素。注:使用STL的vector時,可以利用函數 max_element,min_element,distance可以獲取Vector中最大、最小值的值和位置索引,如下:

int main{
    std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};  
    std::vector<double>::iterator biggest = std::max_element(std::begin(v), std::end(v));  
    std::cout << "Max element is " << *biggest<< " at position " << std::distance(std::begin(v), biggest) << std::endl;
    return 0;
}     

Code:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        int n = findNums.size();
        vector<int>::iterator it;
        vector<int> NGE(n);
        for(int i=0; i<n; i++){
            it = find(nums.begin(),nums.end(),findNums[i]);
            int j = distance(nums.begin(),it)+1;
            for(j; j<nums.size(); j++){
                if(nums[j]>findNums[i]){
                    NGE[i]=nums[j];
                    break;
                } 
            }
            if(j==nums.size()) NGE[i]=-1;
        }
        return NGE;
    }
};

實現二:

使用stack+unordered_map,因爲nums1是nums2的子集,所以要找nums1中元素在nums2中的“下一個大的元素”,只需要對nums2中元素建立<當前元素,下一個大的元素>對應關係。使用unordered_map<int, int> m來存放對應關係,使用stack來幫助建立對應關係。m.count()返回匹配給定主鍵的元素的個數。

Code:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        stack<int> s;
        unordered_map<int, int> m;
        for (int n : nums) {
            while (s.size() && s.top() < n) {
                m[s.top()] = n;
                s.pop();
            }
            s.push(n);
        }
        vector<int> ans;
        for (int n : findNums) ans.push_back(m.count(n) ? m[n] : -1);
        return ans;
    }
};





發佈了28 篇原創文章 · 獲贊 1 · 訪問量 5399
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章