File tree Expand file tree Collapse file tree 3 files changed +21
-22
lines changed Expand file tree Collapse file tree 3 files changed +21
-22
lines changed Original file line number Diff line number Diff line change 1
- /**
2
- * https://leetcode.com/articles/linked-list-cycle/
3
- */
4
-
5
1
public class LinkedListCycle {
6
2
3
+ // 注意判空
7
4
public boolean hasCycle (ListNode head ) {
8
5
for (ListNode fast = head , slow = head ; fast != null && fast .next != null ; ) {
9
6
slow = slow .next ;
Original file line number Diff line number Diff line change @@ -2,27 +2,23 @@ public class MaximumSubarray {
2
2
3
3
// dp[i]表示包含第i个元素时的最大和
4
4
public int maxSubArray (int [] nums ) {
5
- if (nums .length == 0 ) {
6
- return 0 ;
7
- }
8
5
int [] dp = new int [nums .length ];
9
6
int max = Integer .MIN_VALUE ;
10
7
for (int i = 0 ; i < nums .length ; i ++) {
11
- dp [i ] = nums [i ];
12
- if (i > 0 && dp [i - 1 ] > 0 ) {
13
- dp [i ] += dp [i - 1 ];
14
- }
8
+ dp [i ] = Math .max (i > 0 ? dp [i - 1 ] + nums [i ] : nums [i ], nums [i ]);
15
9
max = Math .max (max , dp [i ]);
16
10
}
17
11
return max ;
18
12
}
19
13
20
- public int maxSubArray2 (int [] nums ) {
14
+ /* 这里dp其实可以去掉,换成一个普通int变量即可
15
+ public int maxSubArray(int[] nums) {
21
16
int max = Integer.MIN_VALUE, prev = 0;
22
17
for (int i = 0; i < nums.length; i++) {
23
- prev = Math .max (nums [i ], nums [i ] + prev );
18
+ prev = Math.max(i > 0 ? prev + nums[i] : nums[i], nums[i] );
24
19
max = Math.max(max, prev);
25
20
}
26
21
return max;
27
22
}
23
+ */
28
24
}
Original file line number Diff line number Diff line change 2
2
3
3
public class Main {
4
4
5
- public int maxArea (int [] height ) {
6
- int max = 0 ;
7
- for (int i = 0 , j = height .length - 1 ; i < j ; ) {
8
- max = Math .max (max , Math .min (height [i ], height [j ]) * (j - i ));
9
- if (height [i ] < height [j ]) {
10
- i ++;
11
- } else {
12
- j --;
13
- }
5
+ public int maxSubArray (int [] nums ) {
6
+ int [] dp = new int [nums .length ];
7
+ int max = Integer .MIN_VALUE ;
8
+ for (int i = 0 ; i < nums .length ; i ++) {
9
+ dp [i ] = Math .max (i > 0 ? dp [i - 1 ] + nums [i ] : nums [i ], nums [i ]);
10
+ max = Math .max (max , dp [i ]);
11
+ }
12
+ return max ;
13
+ }
14
+
15
+ public int maxSubArray2 (int [] nums ) {
16
+ int max = Integer .MIN_VALUE , prev = 0 ;
17
+ for (int i = 0 ; i < nums .length ; i ++) {
18
+ prev = Math .max (i > 0 ? prev + nums [i ] : nums [i ], nums [i ]);
19
+ max = Math .max (max , prev );
14
20
}
15
21
return max ;
16
22
}
You can’t perform that action at this time.
0 commit comments