Skip to content

Commit 329a755

Browse files
committed
852. Peak Index in a Mountain Array
1 parent dcd730b commit 329a755

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,7 @@
234234
| 839 | Similar String Groups | [Ruby](./algorithms/ruby/0839-similar-string-groups.rb) | Hard |
235235
| 841 | Backspace String Compare | [Ruby](./algorithms/ruby/0841-keys-and-rooms.rb) | Medium |
236236
| 844 | Backspace String Compare | [Ruby](./algorithms/ruby/0844-backspace-string-compare.rb) | Easy |
237+
| 852 | Peak Index in a Mountain Array | [Ruby](./algorithms/ruby/0852-peak-index-in-a-mountain-array.rb) | Medium |
237238
| 859 | Buddy Strings | [Ruby](./algorithms/ruby/0859-buddy-strings.rb) | Easy |
238239
| 863 | All Nodes Distance K in Binary Tree | [Ruby](./algorithms/ruby/0863-all-nodes-distance-k-in-binary-tree.rb) | Medium |
239240
| 864 | Backspace String Compare | [Ruby](./algorithms/ruby/0864-shortest-path-to-get-all-keys.rb) | Hard |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# frozen_string_literal: true
2+
3+
# 852. Peak Index in a Mountain Array
4+
# Medium
5+
# https://leetcode.com/problems/peak-index-in-a-mountain-array
6+
7+
=begin
8+
An array arr a mountain if the following properties hold:
9+
* arr.length >= 3
10+
* There exists some i with 0 < i < arr.length - 1 such that:
11+
* arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
12+
* arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
13+
Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].
14+
You must solve it in O(log(arr.length)) time complexity.
15+
16+
Example 1:
17+
Input: arr = [0,1,0]
18+
Output: 1
19+
20+
Example 2:
21+
Input: arr = [0,2,1,0]
22+
Output: 1
23+
24+
Example 3:
25+
Input: arr = [0,10,5,2]
26+
Output: 1
27+
28+
Constraints:
29+
* 3 <= arr.length <= 105
30+
* 0 <= arr[i] <= 106
31+
* arr is guaranteed to be a mountain array.
32+
=end
33+
34+
# @param {Integer[]} arr
35+
# @return {Integer}
36+
def peak_index_in_mountain_array(arr)
37+
low = 0
38+
high = arr.length - 1
39+
40+
while low < high
41+
mid = low + (high - low) / 2
42+
43+
if arr[mid] < arr[mid + 1]
44+
low = mid + 1
45+
else
46+
high = mid
47+
end
48+
end
49+
50+
low
51+
end
52+
53+
# **************** #
54+
# TEST #
55+
# **************** #
56+
57+
require "test/unit"
58+
class Test_peak_index_in_mountain_array < Test::Unit::TestCase
59+
def test_
60+
assert_equal 1, peak_index_in_mountain_array([0, 1, 0])
61+
assert_equal 1, peak_index_in_mountain_array([0, 2, 1, 0])
62+
assert_equal 1, peak_index_in_mountain_array([0, 10, 5, 2])
63+
end
64+
end

0 commit comments

Comments
 (0)