Python编程题12--列表中比前面元素都大,比后面元素都小的

2020-10-07  本文已影响0人  wintests

题目

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

实现思路1

代码实现

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

代码实现

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))

更多Python编程题,等你来挑战:Python编程题汇总(持续更新中……)

上一篇下一篇

猜你喜欢

热点阅读