我的方法还是比较传统的思想:
先升后降 ------------ 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;
}
}