2018年2月4日 星期日

[LeetCode] 496. Next Greater Element I

轉自LeetCode

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.
Note:
  1. All elements in nums1 and nums2 are unique.
  2. The length of both nums1 and nums2 would not exceed 1000.
<Solution>

想法如下
  • 先針對 nums2 做歷遍,用 hashmap 記錄每個 element 的 next greater element 是什麼,然用一個 stack 當輔助
  • 例如 nums2 = [1,3,4,2],因為 stack 為空,直接把 1 放到 stack。接下來是 3,因為 stack 不為空,檢查 stack.top 的值(目前是 1) 是不是小於 3,是的話,就記錄 stack.top 這個值的 next greater element 是 3,然後 pop,重複直到 stack 為空,然後再把 3 push 到 stack。接下來是 4,和上個情況一樣。最後是 2,因為 stack.top 目前是 4,比 2 大,所以單純把 2 放到 stack 就好
  • 最後檢查 map,有值的就填值,沒值的就填 -1
code 如下(參考解法)

C++
Java

kotlin

沒有留言:

張貼留言