[LeetCode]#496. Next Greater Element I

Fatboy Slim
2 min readFeb 19, 2021

Environment: Python 3.8

Key technique: list .index

You are given two integer arrays nums1 and nums2 both of unique elements, where nums1 is a 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, return -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.

Analysis:

  1. get the nums1 value index in nums2
  2. check index +1 number in nums2 is larger than nums1 or not.
  3. if yes, return current value. if no, return -1.

Solution:

class Solution:
def nextGreaterElement(self,nums1, nums2):
ans=[-1]*len(nums1)

for i in nums1:
temp=nums2.index(i)
for j in range(temp,len(nums2)):
ans[nums1.index(i)]=-1
if nums2[j]>i:
ans[nums1.index(i)]=nums2[j]
break
return ans

Submissions:

Reference:

https://leetcode.com/problems/next-greater-element-i/discuss/1063834/Simple-python

--

--