关于leetcode上:下一个更大元素的几种解法

第一种 使用栈配合哈希表

主要过程:遍历nums2,首先如果栈为空则直接入栈,如果不为空则判断以下该值与栈首的值哪个大如果栈首的大则继续入栈,如果栈首的小则把两个值加到哈希表中。 接下来把所有的值都判断一遍以后,遍历nums1如果值在哈希表中则输出这个值,如果不在则输出-1。

from collections import deque
class Solution(object):
    def nextGreaterElement(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        s = deque()
        d = {}
        for i in nums2:
            while s and s[-1] < i:
                d[s.pop()] = i
            s.append(i)
        return [d[i] if i in d else -1 for i in nums1]

第二种:while循环加哈希表

首先建立 num2的值与索引之间的哈希表。然后遍历nums1找到它在nums2中的对应位置,往后查找比他大的值然后输出,如果找到最后也没有则输出-1。

 1 class Solution(object):
 2     def nextGreaterElement(self, nums1, nums2):
 3         """
 4         :type nums1: List[int]
 5         :type nums2: List[int]
 6         :rtype: List[int]
 7         """
 8         s = {}
 9         large_num = list()
10         len_2 = len(nums2)
11         for i, j in enumerate(nums2):
12             s[j] = i
13         for i in nums1:
14             index = s[i] + 1
15             while index < len_2:
16                 if nums2[index] > i:
17                     large_num.append(nums2[index])
18                     break
19                 else:
20                     index += 1
21             else:
22                 large_num.append(-1)
23         return large_num

 leetcode:https://leetcode-cn.com/problems/next-greater-element-i/submissions/

github:https://github.com/pythonkd/python/blob/master/LeetCode/nextGreaterElement-1.py

https://github.com/pythonkd/python/blob/master/LeetCode/nextGreaterElement-2.py

猜你喜欢

转载自www.cnblogs.com/python-zkp/p/10517204.html