[抄题]:

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.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

[暴力解法]:

时间分析:

空间分析:新建res数组存nums1的结果

[优化后]:

时间分析:

空间分析:反正是查询index,就地存储即可

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

感觉用stack的题都挺难的,基本靠背。总结下。

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. stack应该搭配while循环,别粗心写成if

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

stack当备胎池,有用的结果有选择性地放在别的地方

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

stack当备胎池,只有最上端开口,只处理当下元素

有用的结果有选择性地放在hashmap里

[关键模板化代码]:

[其他解法]:

[Follow Up]:

Next Greater Element II 还是用stack

[LC给出的题目变变变]:

[代码风格] :

class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
//ini: stack, map
Stack<Integer> stack = new Stack<>();
Map<Integer, Integer> map = new HashMap<>(); //store in stack and map
for (int num : nums2) {
//bigger,put into map
while (!stack.isEmpty() && num > stack.peek()) {
map.put(stack.pop(), num);
}
stack.push(num);
} //get res from map
for (int i = 0; i < nums1.length; i++) {
nums1[i] = map.getOrDefault(nums1[i], -1);
} //return
return nums1;
}
}

最新文章

  1. maven项目断点依赖maven插件
  2. WIN32/API/SDK/MFC四者之间的联系和区别
  3. Leetcode: Sequence Reconstruction
  4. Asp.net mvc中的Ajax处理
  5. The big deffrence between ($(du * )) and $(du *)
  6. ORACLE RAC NTP 时间服务器配置
  7. 记一次ftp服务器错误 centOS 6.4 vsftpd 500 illegal port command
  8. Unix环境高级编程
  9. 在线词典php
  10. Java数据结构之Map学习总结
  11. mysql之连接查询小作业
  12. Java并发编程学习:线程安全与锁优化
  13. C# json解析
  14. 基于散列的集合 HashSet\HashMap\HashTable
  15. iPhone/iPad被停用怎么办 3招轻松解锁
  16. 表单提交.serialize()方法
  17. 关于IT个人看法
  18. 网络虚拟化 SDN
  19. 二叉树的遍历python 代码
  20. AndroidManifest.xml文件详解(uses-feature)

热门文章

  1. Java中数据库连接池原理机制的详细讲解(转)
  2. 剑指offer-第四章解决面试题的思路(从上往下打印二叉树)
  3. IQ/OQ/DQ/PQ
  4. LeetCode Complex Number Multiplication
  5. UVA10674 Tangents
  6. CODEVS4650 破损的键盘
  7. 一个苹果证书如何多次使用——导出p12文件[多台电脑使用]
  8. COGS 2259 异化多肽——生成函数+多项式求逆
  9. 洛谷【P1757】通天之分组背包
  10. flask之flask-restful