zoukankan      html  css  js  c++  java
  • leetcode算法:Next Greater Element I

    You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are 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, output -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:
    All elements in nums1 and nums2 are unique.
    The length of both nums1 and nums2 would not exceed 1000.


    这题描述的需求是:
    给我们两个数组 比如 nums1 = [1,2,3] nums2 = [1,2,3,4,5,6]
    需要我们求出的结果也是一个数组,这个数组,里面的数值一次是:
      对num1里面每一个数字x ,找到在num2里x出现的右侧最近的一个比x大的数字。
      如过nums里x的右侧没有比x大的 就用-1代表这个数字的结果

    比如:
    Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
    Output: [-1,3,-1]
    4在num2中的右侧没有比4大的 所以结果是-1
    1在num2中 右侧最近的比他大的是3
    2在num2中没有右侧数字了 结果是-1


    我的python代码:
     1 class Solution(object):
     2     def nextGreaterElement(self, findNums, nums):
     3         """
     4         :type findNums: List[int]
     5         :type nums: List[int]
     6         :rtype: List[int]
     7         """
     8         res = []
     9         for i in findNums:
    10             index = nums.index(i)
    11             index2 = -1
    12             for j in range(index + 1, len(nums)):
    13                 if nums[j] > i:
    14                     index2 = j
    15                     break
    16             if index2 == -1:
    17                 res.append(-1)
    18             else :
    19                 res.append( nums[index2])
    20         return res
    21 
    22 
    23 
    24 
    25 if __name__ == '__main__':
    26     s = Solution()
    27     res = s.nextGreaterElement([4,1,2], [1,3,4,2] )
    28     print(res)














  • 相关阅读:
    Jupyter Notebook 编辑器美化
    Python3 与 C# 基础语法对比(List、Tuple、Dict、Set专栏)
    Ubuntu 18.04 安装微信(附企业微信)
    区块链概念
    Python3 与 C# 基础语法对比(String专栏)
    用Python3、NetCore、Shell分别开发一个Ubuntu版的定时提醒(附NetCore跨平台两种发布方式)
    ArchLinux 设置时间同步和硬件时间同步错误 No usable clock interface found
    ArchLinux dwm的安装和配置
    POJ-1182 食物链 并查集(互相关联的并查集写法)
    POJ-2236 Wireless Network 并查集
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/7501804.html
Copyright © 2011-2022 走看看