File tree Expand file tree Collapse file tree 3 files changed +62
-0
lines changed Expand file tree Collapse file tree 3 files changed +62
-0
lines changed Original file line number Diff line number Diff line change 86
86
152. 乘积最大子数组
87
87
155. 最小栈
88
88
160. 相交链表
89
+ 162. 寻找峰值
89
90
165. 比较版本号
90
91
169. 多数元素
91
92
188. 买卖股票的最佳时机 IV
Original file line number Diff line number Diff line change 170
170
88. 合并两个有序数组(排序,双指针)
171
171
128. 最长连续序列(集合,排序)
172
172
136. 只出现一次的数字(哈希表,列表,位运算)
173
+ 162. 寻找峰值(二分查找)
173
174
169. 多数元素(排序,哈希表,投票,计数,分治)
174
175
215. 数组中的第K个最大元素(快速排序,堆排序)
175
176
238. 除自身以外数组的乘积(前缀和)
Original file line number Diff line number Diff line change
1
+ // 162. 寻找峰值
2
+
3
+
4
+ /*
5
+ 二分查找:
6
+ 1、二分查找的合理性
7
+ 1)对于任意数组而言,一定存在峰值,因为 nums[0] = nums[n] = -∞
8
+ 2)二分不会错过峰值,因为每次分段查找选择更高的一部分,最终的找到的位置其左右相邻值一定比它低
9
+ 2、计算中点位置时,(left+right)/2 取整计算,中点位置可能在左边界,一定不可能在右边界,中点位置右边的元素一定存在,所以比较元素时要跟右边元素比较
10
+ 3、mid 和 mid+1 位置的元素比较,谁大就以谁为新边界。左元素大就继续到左半部分找、右元素大就到右半部分找。
11
+
12
+ 1 2 3 1
13
+ ↑ ↑ ↑
14
+ l mid r
15
+ ============
16
+ 1 2 3 1
17
+ ↑ ↑
18
+ l/mid r
19
+ ============
20
+ 1 2 3 1
21
+ ↑
22
+ l/r
23
+ */
24
+ class Solution {
25
+ public int findPeakElement (int [] nums ) {
26
+ int left = 0 , right = nums .length - 1 ;
27
+ while (left < right ) {
28
+ int mid = (left + right ) / 2 ;
29
+ if (nums [mid ] > nums [mid + 1 ]) {
30
+ right = mid ;
31
+ } else {
32
+ left = mid + 1 ;
33
+ }
34
+ }
35
+ return left ;
36
+ }
37
+ }
38
+
39
+
40
+ /*
41
+ 一次遍历,判断当前位置是否高于左右两边
42
+ */
43
+ class Solution {
44
+ public int findPeakElement (int [] nums ) {
45
+ int n = nums .length ;
46
+ for (int i = 0 ; i < n ; i ++) {
47
+ boolean flag = true ;
48
+ if (i - 1 >= 0 && nums [i - 1 ] > nums [i ]) {
49
+ flag = false ;
50
+ }
51
+ if (i + 1 < n && nums [i ] < nums [i + 1 ]) {
52
+ flag = false ;
53
+ }
54
+ if (flag ) {
55
+ return i ;
56
+ }
57
+ }
58
+ return -1 ;
59
+ }
60
+ }
You can’t perform that action at this time.
0 commit comments