ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

leetcode 496. Next Greater Element I(python)

2021-06-05 13:00:47  阅读:193  来源: 互联网

标签:Greater python number Element result array nums1 nums2 greater


描述

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.

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 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 10^4
All integers in nums1 and nums2 are unique.
All the integers of nums1 also appear in nums2.

解析

根据题意,num1 是 num2 的子集,找出 num1 中每个元素在 num2 中的对应位置之后的第一个大于它的数,如果没有则结果为 -1 。我这里定义了一个方法 find ,就是为了在 num2 中的 idx 位置之后找比 nums2[idx] 大的数字。直接遍历 num1 ,得到元素在 num2 中的索引,然后使用我定义的 find 函数,得到的结果追加到 result 中,遍历结束即可得到结果。

解答

class Solution(object):
    def nextGreaterElement(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        def find(A, idx):
            result = -1
            for i in range(idx, len(A)):
                if A[i]>A[idx]:
                    result = A[i]
                    break
            return result
        result = []
        for n in nums1:
            idx = nums2.index(n)
            result.append(find(nums2, idx))
        return result

运行结果

Runtime: 80 ms, faster than 21.98% of Python online submissions for Next Greater Element I.
Memory Usage: 13.3 MB, less than 100.00% of Python online submissions for Next Greater Element I.

原题链接:https://leetcode.com/problems/next-greater-element-i

您的支持是我最大的动力

标签:Greater,python,number,Element,result,array,nums1,nums2,greater
来源: https://blog.csdn.net/wang7075202/article/details/117592311

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有