← Static tasks

852. Peak Index in a Mountain Array

leetcode

#array#csharp#leetcode

Task

: medium

Вам дан целочисленный массив горы arr длины n, где значения увеличиваются до пикового элемента, а затем уменьшаются.

Верните индекс пикового элемента.

Ваша задача — решить это с временной сложностью O(log(n)).

Пример:

Input: arr = [0,1,0]

Output: 1

C# solution

matched/original
public class Solution {
    public int PeakIndexInMountainArray(int[] arr) {
        int i = 0;
        while (arr[i] < arr[i + 1]) {
            i++;
        }
        return i;
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int PeakIndexInMountainArray(vector<int>& arr) {
        int i = 0;
        while (arr[i] < arr[i + 1]) {
            i++;
        }
        return i;
    }
}

Java solution

matched/original
class Solution {
    public int peakIndexInMountainArray(int[] arr) {
        int i = 0;
        while (arr[i] < arr[i + 1]) {
            i++;
        }
        return i;
    }
}

JavaScript solution

matched/original
var peakIndexInMountainArray = function(arr) {
    let i = 0
    while (arr[i] < arr[i + 1]) {
        i++
    }
    return i
}

Go solution

matched/original
func peakIndexInMountainArray(arr []int) int {
    i := 0
    for arr[i] < arr[i+1] {
        i++
    }
    return i
}

Explanation

Algorithm

Создайте целочисленную переменную i и инициализируйте её значением 0.

Используя цикл while, проверьте, если текущий элемент, на который указывает i, меньше следующего элемента на индексе i + 1. Если arr[i] < arr[i + 1], увеличьте i на 1.

В противном случае, если arr[i] > arr[i + 1], верните i.

😎