Class Solution

java.lang.Object
g0401_0500.s0496_next_greater_element_i.Solution

public class Solution extends Object
496 - Next Greater Element I.<p>Easy</p> <p>The <strong>next greater element</strong> of some element <code>x</code> in an array is the <strong>first greater</strong> element that is <strong>to the right</strong> of <code>x</code> in the same array.</p> <p>You are given two <strong>distinct 0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, where <code>nums1</code> is a subset of <code>nums2</code>.</p> <p>For each <code>0 <= i < nums1.length</code>, find the index <code>j</code> such that <code>nums1[i] == nums2[j]</code> and determine the <strong>next greater element</strong> of <code>nums2[j]</code> in <code>nums2</code>. If there is no next greater element, then the answer for this query is <code>-1</code>.</p> <p>Return <em>an array</em> <code>ans</code> <em>of length</em> <code>nums1.length</code> <em>such that</em> <code>ans[i]</code> <em>is the <strong>next greater element</strong> as described above.</em></p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]</p> <p><strong>Output:</strong> [-1,3,-1]</p> <p><strong>Explanation:</strong></p> <p>The next greater element for each value of nums1 is as follows:</p> <ul> <li> <p>4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.</p> </li> <li> <p>1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.</p> </li> <li> <p>2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.</p> </li> </ul> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> nums1 = [2,4], nums2 = [1,2,3,4]</p> <p><strong>Output:</strong> [3,-1]</p> <p><strong>Explanation:</strong></p> <p>The next greater element for each value of nums1 is as follows:</p> <ul> <li> <p>2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.</p> </li> <li> <p>4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.</p> </li> </ul> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= nums1.length <= nums2.length <= 1000</code></li> <li><code>0 <= nums1[i], nums2[i] <= 10<sup>4</sup></code></li> <li>All integers in <code>nums1</code> and <code>nums2</code> are <strong>unique</strong>.</li> <li>All the integers of <code>nums1</code> also appear in <code>nums2</code>.</li> </ul> <p><strong>Follow up:</strong> Could you find an <code>O(nums1.length + nums2.length)</code> solution?</p>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • nextGreaterElement

      public int[] nextGreaterElement(int[] nums1, int[] nums2)