用 Python 编写程序从数字列表中查找局部峰值元素索引

pythonserver side programmingprogramming更新于 2025/12/17 22:04:17

假设我们有一个名为 nums 的数字列表,其长度至少为 2。我们必须找到列表中每个峰值的索引。该列表按升序排序。当 − 时,索引 i 是峰值

  • 当 i = 0 时,nums[i] > nums[i + 1]

  • 当 i = n - 1 时,nums[i] > nums[i - 1]

  • nums[i - 1] < nums[i] > nums[i + 1] else

因此,如果输入为 nums = [5, 6, 7, 6, 9],则输出将为 [2, 4],因为索引 2 处的元素为 7,大于两个邻居,而索引 4 处的项目为 9,这大于其左侧项目。

为了解决这个问题,我们将遵循以下步骤 −

  • ans := 一个新列表

  • n := nums 的大小

  • 如果 n 与 1 相同,则

    • 返回 ans

  • 对于 nums 中的每个索引 i 和数字 num,执行

    • 如果 i > 0 且 i < n - 1,则

      • 如果 nums[i - 1] < num > nums[i + 1],则

        • 在 ans 末尾插入 i

      • 如果 i 与 0 相同,则

        • 如果 num > nums[i + 1],则

          • 在 ans 末尾插入 i

      • 如果 i 与 n - 1 相同,则

        • 如果 num > nums[i - 1],然后

          • 在 ans 末尾插入 i

  • 返回 ans

示例

让我们看看下面的实现以便更好地理解

def solve(nums):
   ans = []
   n = len(nums)

   if n == 1:
      return ans

   for i, num in enumerate(nums):
      if i > 0 and i < n - 1:
         if nums[i - 1] < num > nums[i + 1]:
            ans.append(i)

      if i == 0:
         if num > nums[i + 1]:
            ans.append(i)

      if i == n - 1:
         if num > nums[i - 1]:
            ans.append(i)

   return ans

nums = [5, 6, 7, 6, 9]
print(solve(nums))

输入

[5, 6, 7, 6, 9]

输出

[2, 4]

相关文章


有用资源