-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-162-Find-Peak-Element.java
90 lines (78 loc) · 2.57 KB
/
LeetCode-162-Find-Peak-Element.java
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
88
89
90
class Solution {
// 1. Brute Force, just scan the nums, find the peak
/*
Time O(N)
Space O(1)
*/
// public int findPeakElement(int[] nums) {
// int result = 0;
// if (nums == null || nums.length == 0) return 0;
// if (nums.length == 1) return 0;
// if (nums.length == 2) {
// if (nums[0] == nums[1]) return -1;
// else if (nums[0] < nums[1]) return 1;
// else return 0;
// }
// int n = nums.length;
// if (nums[0] > nums[1]) return 0;
// if (nums[n - 2] < nums[n - 1]) return n - 1;
// for (int i = 1; i < nums.length - 1; i++) {
// if (nums[i - 1] < nums[i] && nums[i] > nums[i + 1]) return i;
// }
// return -1;
// }
// 2.Binary Search
/*
Time O(N)
Space O(1)
*/
// public int findPeakElement(int[] nums) {
// int lo = 0, hi = nums.length-1;
// while(lo < hi){
// if(lo + 1 == hi)
// return nums[lo] > nums[hi] ? lo : hi;
// int mid = lo + (hi - lo) / 2;
// if(nums[mid-1] < nums[mid] && nums[mid] > nums[mid+1])
// return mid;
// else if(nums[mid-1] < nums[mid] && nums[mid] < nums[mid+1])
// lo = mid + 1;
// else
// hi = mid - 1;
// }
// return lo;
// }
// 3.Binary Search
/*
Time O(N)
Space O(1)
*/
public int findPeakElement(int[] nums) {
int lo = 0, hi = nums.length - 1;
while (lo + 1 < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1]) {
return mid;
} else if (nums[mid - 1] < nums[mid] && nums[mid] < nums[mid + 1]) {
lo = mid;
} else {
hi = mid;
}
}
return nums[lo] > nums[hi] ? lo : hi;
}
// doesn't work
// public int findPeakElement(int[] nums) {
// int lo = 0, hi = nums.length - 1;
// while (lo <= hi) {
// int mid = lo + (hi - lo) / 2;
// if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1]) {
// return mid;
// } else if (nums[mid - 1] < nums[mid] && nums[mid] < nums[mid + 1]) {
// lo = mid + 1;
// } else {
// hi = mid - 1;
// }
// }
// return nums[lo] > nums[hi] ? lo : hi;
// }
}