首页 > 学院 > 开发设计 > 正文

[LeetCode]496. Next Greater Element I

2019-11-06 06:39:04
字体:
来源:转载
供稿:网友

[LeetCode]496. Next Greater Element I

题目描述

这里写图片描述

思路

对每个数,遍历找到在目标数组中的位子,然后在位子之后找比他大的数,找到即寻找下一个数 update 使用栈和map 对于在nums中出现的每个数,在map中保存<这个数,该位置之后的第一个比他大的数>,然后再遍历findNums,用map确定每一位对应的值,不存在的对应-1

代码

class Solution {public: vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { vector<int> result; for (int i = 0; i < findNums.size(); ++i){ int finded = -1, flag = -1; for (int j = 0; j < nums.size(); ++j) { if (flag != -1 && nums[j] > nums[flag]) { finded = nums[j]; break; } if (findNums[i] == nums[j]){ flag = j; } } result.push_back(finded); } return result; }};

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; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表