forked from super30admin/Binary-Search-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPeakElement.txt
87 lines (49 loc) · 1.58 KB
/
PeakElement.txt
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
// Time Complexity : O(log n)
// Space Complexity :O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : Had to search the algorithm to implement Optimized solution
class Solution {
public int findPeakElement(int[] nums) {
/*
Brute force
int i = 1;
int j = nums.length - 1;
if (nums.length == 1)
return 0;
if (nums[0] > nums[1]){
return 0;
}
if ( nums[j] > nums[j -1]){
return j;
}
while ( i < j ){
if (nums[i] > nums[i-1] &&
nums[i] > nums[i+1]){
return i;
}
}
return -1;
*/
if (nums.length == 1) {
return 0;
}
if (nums[0] > nums[1]){
return 0;
}
if ( nums[nums.length - 1] > nums[nums.length - 2]){
return nums.length - 1;
}
int low = 0;
int high = nums.length - 1;
while (low < high ){
int mid = low + (high - low)/2 ;
if (nums[mid] > nums[mid + 1]){
high = mid;
}
else {
low = mid + 1;
}
}
return low;
}
}