参考:
https://leetcode-cn.com/problems/next-greater-element-i/solution/xia-yi-ge-geng-da-yuan-su-i-by-leetcode/
package T496下一个更大元素I;
import java.util.HashMap;
public class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums2.length; i++) {
map.put(nums2[i], i);
}
int[] result = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
boolean flag = false;
int start = map.get(nums1[i]);
for (int j = start+1; j < nums2.length; j++) {
if (nums2[j] > nums1[i]) {
result[i] = nums2[j];
flag = true;
break;
}
}
if (!flag) {
result[i] = -1;
}
}
return result;
}
}
```
class Solution:
def nextGreaterElement(self, nums1, nums2):
m = dict()
nums2_len = len(nums2)
for index, num in enumerate(nums2):
m[num] = index
result = list()
for i in nums1:
index = m[i]
# 是否找到更大的值
flag = False
for next_num_index in range(index,nums2_len):
if nums2[next_num_index] > i:
result.append(nums2[next_num_index])
flag = True
break
if flag is False:
result.append(-1)
return result
if __name__ == '__main__':
x = Solution()
nums1 = [4, 1, 2]
nums2 = [1, 3, 4, 2]
print(x.nextGreaterElement(nums1, nums2))