852. 山脉数组的峰顶索引 (二分查找)

本文提供了两种使用C#解决寻找山峰数组中峰值索引问题的方法。第一种方法通过遍历数组,判断升序和降序部分来找到峰值位置。第二种方法采用位移技巧,通过比较中间元素与其相邻元素,高效地定位峰值,显著提高了执行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的方法还是比较传统的思想:

先升后降   ------------ A 字型

提供c#答案如下: 

执行用时: 268 ms, 在Peak Index in a Mountain Array的C#提交中击败了7.23% 的用户

public class Solution {
    public int PeakIndexInMountainArray(int[] A) {
        int res = -1;
			int temp = 0;bool b = true;
			temp = A[0];
			if (A.Length < 3 || A.Length > 10000) return -1;
			for (int i = 1; i < A.Length; i++)
			{
				#region 升序过程
				if (A[i] >= temp && b == true)
				{
					temp = A[i];
				}
				else
				{
					b = false;
				}
				#endregion
				#region 降序过程
				if (A[i]<=temp&&b==false)
				{
					temp = A[i];
				}
				else
				{
					  res = i;
				}
				#endregion
			}
			return res;
    }
}

 

提供第二种c#方法:(位移)

执行用时: 120 ms, 在Peak Index in a Mountain Array的C#提交中击败了86.87% 的用户

public class Solution {
    public int PeakIndexInMountainArray(int[] A) {
        int l = 0, h = A.Length - 1, m;
			while (l<h)
			{
				m = l + h >> 1;
				if (A[m] > A[m - 1] && A[m] > A[m + 1])
				{
					return m;
				}
				else if (A[m] > A[m - 1] && A[m] < A[m + 1])
				{
					l = m;
				}
				else if (A[m] < A[m - 1] && A[m] > A[m + 1])
				{
					h = m;
				}
				else
				{
					return -1;
				}
			}
			return -1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值