zoukankan      html  css  js  c++  java
  • Python编程题12--列表中比前面元素都大,比后面元素都小的数

    题目

    给定一个无序列表,列表中元素均为不重复的整数。请找出列表中有没有比它前面元素都大,比它后面的元素都小的数,如果不存在则返回-1,存在则显示其索引。

    实现思路1

    • 利用 列表 结合 max()min() 内置函数来实现
    • 遍历列表,并通过 max()min() 分别求出当前元素在列表左侧的最小数、在列表右侧的最大数
    • 比较当前元素,是否满足比前面元素都大,比后面元素都小的条件,如果符合则将其对应的索引下标添加到结果列表中

    代码实现

    def find_number_index(nums):
        if len(nums) < 1:
            return -1
        res = []
        for i in range(len(nums)):
            left_max, right_min = max(nums[:i+1]), min(nums[i:])
            if nums[i] >= left_max and nums[i] <= right_min:
                res.append(i)
        return res if res else -1
    
    nums = [21, 11, 45, 56, 9, 66, 77, 89, 78, 68, 100, 120, 111]
    print(find_number_index(nums))
    

    实现思路2

    • 设置一个额外的列表 right_min_list ,倒序遍历原始列表,用于存储原始列表中每个元素从右到左的最小值 right_min
    • 设置一个额外的列表 left_max_list ,正序遍历原始列表,用于存储原始列表中每个元素从左到右的最大值 left_max
    • 对第一步中额外的列表 right_min_list ,进行反转
    • 正序遍历原始列表,对比 left_max_list 和 right_min_list 在相同索引下标的元素是否一致,如果一致则说明该元素满足条件

    代码实现

    def find_number_index(nums):
        if len(nums) < 1:
            return -1
        res, right_min_list = [], []
        right_min = nums[-1]
        for i in range(len(nums) - 1, -1, -1): # 倒序遍历
            if right_min > nums[i]:
                right_min = nums[i]
            right_min_list.append(right_min)
        left_max_list = []
        left_max = nums[0]
        for i in range(0, len(nums)):
            if left_max < nums[i]:
                left_max = nums[i]
            left_max_list.append(left_max)
            if left_max_list[i] == right_min_list[::-1][i]:
                res.append(i)
        return res if res else -1
    
    nums = [21, 11, 45, 56, 9, 66, 77, 89, 78, 68, 100, 120, 111]
    print(find_number_index(nums))
    
  • 相关阅读:
    ZOJ 3765 Lights (zju March I)伸展树Splay
    UVA 11922 伸展树Splay 第一题
    UVALive 4794 Sharing Chocolate DP
    ZOJ 3757 Alice and Bod 模拟
    UVALive 3983 捡垃圾的机器人 DP
    UVA 10891 SUM游戏 DP
    poj 1328 Radar Installatio【贪心】
    poj 3264 Balanced Lineup【RMQ-ST查询区间最大最小值之差 +模板应用】
    【转】RMQ-ST算法详解
    poj 3083 Children of the Candy Corn 【条件约束dfs搜索 + bfs搜索】【复习搜索题目一定要看这道题目】
  • 原文地址:https://www.cnblogs.com/wintest/p/13776370.html
Copyright © 2011-2022 走看看