publicintpeakIndexInMountainArray(int[] A){intn = A.length;for(inti=0; i<n-1; i++) {if(A[i] < A[i+1]) {continue; }else{returni; } }return0; } 03 第二种解法 思路和上面一样,也是直接遍历数组元素,进行比较,找到山顶。 publicintpeakIndexInMountainArray(int[] A) {intindex=0;...
classSolution{public:intpeakIndexInMountainArray(vector<int>& A){intn = A.size(), left =0, right = n -1;while(left < right) {intmid = left + (right - left) /2;if(A[mid] < A[mid +1]) left = mid +1;elseright = mid; }returnright; } }; Github 同步地址: https://githu...
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: # 利用给定数组是山脉数组的条件, 二分查找峰顶 # 这里使用1和len-2作为起点和终点, 因为数组开头和结尾肯定不是峰顶 # 这样做还有个好处: 比较相邻数字时无需判断下标, 因为它们一定不越界 s, e = 1, len(arr) - 2 ...
代码实现 class Solution: def peakIndexInMountainArray(self, A): """ :type A: List[int] :rtype: int """ return A.index(max(A)) 1. 2. 3. 4. 5. 6. 7.
var peakIndexInMountainArray = function (arr) { // 定义左右边界 let l = 0, r = arr.length - 1; // 这里不用加=,因为指针还没重合前一定会找到最高的山峰 while (l < r) { let mid = Math.floor(l + (r - l) / 2); // 如果是第二种情况,直接跳出循环 ...
def peakIndexInMountainArray(arr: list[int]) -> int: for i in range(1, len(arr)): # 注意:这里要从1 开始,否则再i-1的时候会有bug if arr[i] < arr[i - 1]: return i - 1 二分查找 当然,我们这是一道二分查找题,使用二分查找可以将时间复杂度降到最低 :O(log n) 回忆下二分查找...
给定一个长度为n的整数山脉数组arr,其中的值递增到一个峰值元素然后递减。 返回峰值元素的下标。 你必须设计并实现时间复杂度为O(log(n))的解决方案。 示例1: 输入:arr = [0,1,0]输出:1 示例2: 输入:arr = [0,2,1,0]输出:1 示例3: 输入:arr = [0,10,5,2]输出:1 ...
A peak element is an element that is greater than its neighbors.Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.You may imagine that...
leetcode-222-Counter Complete Binary Tree Nodes - binary search 2 0 10:00 App leetcode-852. Peak Index in a Mountain Array -binary-search 94 0 10:30 App leetcode-1973-Count Nodes Equal to Sum of Descendants - Recursion 3 0 15:08 App leetcode-111. Minimum Depth of Binary Tree -...
852Peak Index in a Mountain ArrayPythonJava1. Scan the array until encountering decline, O(n) and O(1) 2. Binary seach with additional check for [i + 1], O(logn) and O(1) 867Transpose MatrixPythonJavaRes[i][j] = A[j][i] ...