-
Notifications
You must be signed in to change notification settings - Fork 93
/
PeakElement
87 lines (78 loc) · 2.22 KB
/
PeakElement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package array;
/**
* <b>IDeserve <br>
* <a href="https://www.youtube.com/c/IDeserve">https://www.youtube.com/c/IDeserve</a>
* <br><br>
* Peak Element</b><br>
* Given an array of size n, find a peak element. Peak element is the element which is greater or equal to all its neighbors.<br><br>
* <br><br>
* Ex. Array [1,4,3,6,7,5]
* <br>
* Output: 4
* <br><br>
* <a href="https://www.youtube.com/watch?v=zOyOwDEF1Rc">Peak Element - Youtube Link</a>
* @author Saurabh
*
*/
public class PeakElement {
public static Integer getPeakElement(int[] array) {
if(array == null || array.length == 0) {
return null;
}
int n = array.length;
int start = 0;
int end = n - 1;
while(start <= end) {
int mid = (start+end)/2;
if((mid == 0 || array[mid-1] <= array[mid]) &&
(mid == n-1 || array[mid] >= array[mid+1])) {
return array[mid]; // array[mid] is peak element
}
else {
if(mid>0 && array[mid-1] > array[mid]) {
end = mid-1;
} else {
start = mid+1;
}
}
}
return null;
}
public static void main(String[] args) {
{
int[] array = { 15, 20, 25, 35, 45, 50, 60 };
Integer peak = getPeakElement(array);
System.out.println(peak != null ? "Peak Element is " + peak : "No peak element!");
}
{
int[] array = { 5,4,3,2,1 };
Integer peak = getPeakElement(array);
System.out.println(peak != null ? "Peak Element is " + peak : "No peak element!");
}
{
int[] array = { 1,4,3,6,7,5 };
Integer peak = getPeakElement(array);
System.out.println(peak != null ? "Peak Element is " + peak : "No peak element!");
}
{
int[] array = { 1,3,5,7,6,4,2 };
Integer peak = getPeakElement(array);
System.out.println(peak != null ? "Peak Element is " + peak : "No peak element!");
}
{
int[] array = { 1 };
Integer peak = getPeakElement(array);
System.out.println(peak != null ? "Peak Element is " + peak : "No peak element!");
}
{
int[] array = { };
Integer peak = getPeakElement(array);
System.out.println(peak != null ? "Peak Element is " + peak : "No peak element!");
}
{
int[] array = null;
Integer peak = getPeakElement(array);
System.out.println(peak != null ? "Peak Element is " + peak : "No peak element!");
}
}
}