forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Search] Add a solution to Peak Index in a Mountain Array, update the…
… solution to Find Peak Element
- Loading branch information
Showing
3 changed files
with
35 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/peak-index-in-a-mountain-array/ | ||
* Primary idea: Classic Binary Search | ||
* | ||
* Time Complexity: O(logn), Space Complexity: O(1) | ||
*/ | ||
|
||
|
||
class PeakIndexMountainArray { | ||
func peakIndexInMountainArray(_ A: [Int]) -> Int { | ||
var left = 0, right = A.count - 1, mid = 0 | ||
|
||
while left < right { | ||
mid = (right - left) / 2 + left | ||
|
||
if A[mid] > A[mid + 1] { | ||
right = mid | ||
} else { | ||
left = mid + 1 | ||
} | ||
} | ||
|
||
return left | ||
} | ||
} |