
對(duì)每個(gè)數(shù),遍歷找到在目標(biāo)數(shù)組中的位子,然后在位子之后找比他大的數(shù),找到即尋找下一個(gè)數(shù) update 使用棧和map 對(duì)于在nums中出現(xiàn)的每個(gè)數(shù),在map中保存<這個(gè)數(shù),該位置之后的第一個(gè)比他大的數(shù)>,然后再遍歷findNums,用map確定每一位對(duì)應(yīng)的值,不存在的對(duì)應(yīng)-1
update
class Solution {public: vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { vector<int> result; stack<int> compare; unordered_map<int, int> finded; for (auto &p : nums){ while (compare.size() && compare.top() < p){ finded[compare.top()] = p; compare.pop(); } compare.push(p); } for (auto &p : findNums){ result.push_back(finded.count(p) ? finded[p] : -1); } return result; }};新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注