Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 0d5fdb0

Browse files
solves find peak element in java
1 parent d2a1625 commit 0d5fdb0

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@
143143
| 159 | 🔒 [Longest Substring With At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters) | | |
144144
| 160 | [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists) | [![Java](assets/java.png)](src/IntersectionOf2LinkedLists.java) [![Python](assets/python.png)](python/intersecction_of_two_linked_lists.py) | |
145145
| 161 | 🔒 [One Edit Distance](https://leetcode.com/problems/one-edit-distance) | | |
146-
| 162 | [Find Peak Element](https://leetcode.com/problems/find-peak-element) | | |
146+
| 162 | [Find Peak Element](https://leetcode.com/problems/find-peak-element) | [![Java](assets/java.png)](src/FindPeakElement.java) | |
147147
| 165 | [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers) | | |
148148
| 166 | [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal) | | |
149149
| 167 | [Two Sum II - Input Array is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted) | [![Java](assets/java.png)](src/TwoSumIIInputArrayIsSorted.java) [![Python](assets/python.png)](python/two_sum_ii.py) | |

src/FindPeakElement.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// https://leetcode.com/problems/find-peak-element
2+
// T: O(log(N))
3+
// S: O(1)
4+
5+
public class FindPeakElement {
6+
public static int findPeakElement(int[] array) {
7+
for (int left = 0, right = array.length - 1, middle ; left <= right ; ) {
8+
middle = left + (right - left) / 2;
9+
10+
if (isPeakElement(array, middle)) return middle;
11+
12+
if (isOnIncreasingSlope(array, middle)) left = middle + 1;
13+
else right = middle - 1;
14+
}
15+
return -1;
16+
}
17+
18+
private static boolean isOnIncreasingSlope(int[] array, int index) {
19+
return ((index > 0 && array[index - 1] < array[index]) || index == 0)
20+
&& ((index + 1 < array.length && array[index] < array[index + 1]) || index == array.length - 1);
21+
}
22+
23+
private static boolean isPeakElement(int[] array, int index) {
24+
return ((index > 0 && array[index - 1] < array[index]) || index == 0)
25+
&& ((index + 1 < array.length && array[index + 1] < array[index]) || index == array.length - 1);
26+
}
27+
}

0 commit comments

Comments
 (0)