【C#】山脉数组的峰顶索引

出处:https://blog.csdn.net/qq_43920838/article/details/143427372

public void TestMethod1()
{
    var arr = new[] { 1, 2, 3, 4, 5, 6, 4, 3, 1 };
    var index = FindIndexOfMount(arr);
    Console.WriteLine(arr[index].ToString());
}
public static int FindIndexOfMount(int[] arr)
{
    int left = 0;
    int right = arr.Length - 1;
    while (left < right)
    {
        int mid = (left + right) / 2;
        if (arr[mid] > arr[mid + 1])
        {
            right = mid;
        }
        else
        {
            left = mid + 1;
        }               
    }
    return left;
}
posted @ 2024-11-02 17:58  greencode  阅读(0)  评论(0编辑  收藏  举报