摘要:題目例子我的解法其他解法求最大值然后求二分法查找
1 題目
Let"s call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].
Input: [0,1,0] Output: 1
Input: [0,2,1,0] Output: 1我的解法
var peakIndexInMountainArray = function(A) { let i = 0 while (i < A.length){ if (A[i] > A[i+1]){ break } i++ } return i };
Runtime: 60 ms, faster than 85.20% of JavaScript online submissions for Peak Index in a Mountain Array.其他解法
Memory Usage: 35 MB, less than 52.70% of JavaScript online submissions for Peak Index in a Mountain Array.
var peakIndexInMountainArray = function(A) { return A.indexOf(Math.max(...A)); };
求最大值然后求index
var peakIndexInMountainArray = function(A) { function mid(a,b) { return Math.floor((b-a)/2); } let left = 0, right = A.length-1; let pivot = mid(left, right); while ( A[pivot-1]>A[pivot] || A[pivot]A[pivot+1]) { right = pivot; pivot = mid(left, right) } else { left = pivot; pivot += mid(left, right) } } return pivot; };
二分法查找
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/103537.html
摘要:題目鏈接題目分析這個題目比較簡單。要求返回數(shù)組中最大值的索引。思路先用找到最大值,再用獲取最大值的索引。最終代碼若覺得本文章對你有用,歡迎用愛發(fā)電資助。 852. Peak Index in a Mountain Array 題目鏈接 852. Peak Index in a Mountain Array 題目分析 這個題目比較簡單。要求返回數(shù)組中最大值的索引。 思路 先用max找到最...
Problem Lets call an array A a mountain if the following properties hold: A.length >= 3There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]...
摘要:找出該矩陣的一個峰值元素,返回他的坐標原題鏈接一維二分搜索復(fù)雜度時間空間思路最直觀的方法是遍歷整個矩陣,但這要的時間。 Find Peak Element I A peak element is an element that is greater than its neighbors. Given an input array where num[i] ≠ num[i+1], fi...
摘要:二分迭代法復(fù)雜度時間空間遞歸棧空間思路找旋轉(zhuǎn)數(shù)組的起點,實際上類似找一個山谷,只要兩邊都比中間高就對了,這和這題很像。 Find Minimum in Rotated Sorted Array I Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 ...
Problem Given an integer array sorted in ascending order, write a function to search target in nums. If target exists, then return its index, otherwise return -1. However, the array size is unknown t...
閱讀 1656·2019-08-30 15:55
閱讀 978·2019-08-30 15:44
閱讀 871·2019-08-30 10:48
閱讀 2041·2019-08-29 13:42
閱讀 3188·2019-08-29 11:16
閱讀 1263·2019-08-29 11:09
閱讀 2059·2019-08-26 11:46
閱讀 619·2019-08-26 11:44