File tree Expand file tree Collapse file tree 3 files changed +20
-24
lines changed
solution/src/main/java/com/inuker/solution
test/src/main/java/com/inuker/test Expand file tree Collapse file tree 3 files changed +20
-24
lines changed Original file line number Diff line number Diff line change 8
8
* https://leetcode.com/articles/find-peak-element/
9
9
*/
10
10
public class FindPeakElement {
11
-
11
+ /**
12
+ * 首先局部峰值有很多
13
+ * 1,如果nums[mid]>nums[mid+1],说明当前递减,左边肯定有个峰值,因为如果
14
+ * 没有,则意味着往左走会不停地上升,走到头的时候因为是负无穷,所以也相当于峰值
15
+ * 右边不一定有峰值,因为可能一直是下降趋势
16
+ * 2,如果nums[mid]<nums[mid+1],说明当前是上升趋势,右边肯定有个峰值,理由同上
17
+ * 3,题目说了不存在nums[i]=nums[i+1]的情况
18
+ */
12
19
public int findPeakElement (int [] nums ) {
13
- return Helper (nums , 0 , nums .length - 1 );
14
- }
15
-
16
- private int Helper (int [] nums , int low , int high ) {
17
- if (low == high ) {
18
- return low ;
19
- } else {
20
- int mid1 = (low + high ) / 2 ;
21
- int mid2 = mid1 + 1 ;
22
- if (nums [mid1 ] > nums [mid2 ]) {
23
- return Helper (nums , low , mid1 );
24
- } else {
25
- return Helper (nums , mid2 , high );
26
- }
20
+ int l = 0 , r = nums .length - 1 ;
21
+ while (l < r ) {
22
+ int mid = (l + r ) / 2 ;
23
+ if (nums [mid ] > nums [mid + 1 ])
24
+ r = mid ;
25
+ else
26
+ l = mid + 1 ;
27
27
}
28
+ return l ;
28
29
}
29
30
}
30
31
Original file line number Diff line number Diff line change 7
7
public class MissingNumber {
8
8
9
9
public int missingNumber (int [] nums ) {
10
- int xor = 0 , i = 0 ;
11
- for (i = 0 ; i < nums .length ; i ++) {
12
- xor = xor ^ i ^ nums [i ];
10
+ int xor = nums . length ;
11
+ for (int i = 0 ; i < nums .length ; i ++) {
12
+ xor ^= i ^ nums [i ];
13
13
}
14
-
15
- return xor ^ i ;
14
+ return xor ;
16
15
}
17
16
}
Original file line number Diff line number Diff line change @@ -31,10 +31,6 @@ public static void main(String[] args) {
31
31
int [] arr = new int [] {
32
32
0 , 0 , 3 , 4 , 5 , 0 , 0
33
33
};
34
- new Test2 ().moveZeroes (arr );
35
- for (int n : arr ) {
36
- System .out .print (n + " " );
37
- }
38
34
}
39
35
40
36
}
You can’t perform that action at this time.
0 commit comments