【C#】山脈陣列的峰頂索引

greencode發表於2024-11-02

出處: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;
}

相關文章