想到了用哈希表存这个数的位置,但是没有想到可以直接用哈希表存next great,用栈存还没找到的数,没遍历一个数就考察栈中的元素小,小的话,这个数就是栈中数的next great,栈中的数肯定是下大上小。 publicint[] nextGreaterElement(int[] nums1,int[] nums2) {/*通过map建立当前元素和其next great的映射 ...
1classSolution {2public:3vector<int> secondGreaterElement(vector<int>&nums) {4intn =nums.size();5vector<int>p;6for(inti =0; i < n; i++) {7p.push_back(i);8}9sort(p.begin(), p.end(), [&](inta,intb) {10returnnums[a] >nums[b];11});1213set<int>st;14st.insert(n),...
LeetCode题目:503. Next Greater Element II Given acircular array (the next element of the last element is the first element of the array),print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the...
503. Next Greater Element II # 题目 # Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to
public int[] nextGreaterElement(int[] findNums, int[] nums) { Map<Integer, Integer> map = new HashMap<>(); // map from x to next greater element of x Stack<Integer> stack = new Stack<>(); for (int num : nums) { //pay attention, we use nums2 to constuact our map, and ...
Subscribe to unlock. Thanks for using LeetCode! To view this solution you must subscribe to premium. Subscribe C++ Auto 1 2 3 4 5 6 class Solution { public: int nextGreaterElement(int n) { } }; Saved Ln 1, Col 1 Case 1 Case 2...
额外思考:如果目前栈长这个样子:底4->3, 3.5 过来的话,由于 3.5 大于栈顶的3,那么就把3抽掉;然后用3.5和新的栈顶4对比,发现3.5比4小,所以把3.5和4构成一对新的键值;并把3.5压到栈顶。 3 解题代码 ## LeetCode 496fromtypingimportListclassSolution:defnextGreaterElement(self,nums1:List[int],nums2:...
这个题和之前的503. Next Greater Element II做法一样的,都是使用一个单调递减栈保存每个数字的下标。 首先,把链表遍历一遍,转化成数组问题。 然后遍历数组,需要维护单调递减栈,每个元素的位置都要往栈里面放,放之前先把栈里面小于该元素的全部弹出。
LeetCode笔记:503. Next Greater Element II 问题: Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order ...
下面将使用两种方法来解题,一种是暴力破解法,一种是Next Greater Number问题解法。 2.1、暴力破解法 从头开始遍历nums1,每次遍历从nums2中找到对应元素,然后从该元素的下一个元素开始依次比较,找出大于该值的第一个元素即可。 【代码实现】 class Solution {public int[] nextGreaterElement(int[] nums1, int[]...