Skip to content

Commit 1361e11

Browse files
committed
commit
1 parent 1842fcd commit 1361e11

File tree

2 files changed

+28
-16
lines changed

2 files changed

+28
-16
lines changed

[036][Valid Sudoku]/src/Solution.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import java.util.Arrays;
2+
13
/**
24
* Author: 王俊超
35
* Date: 2015-08-21
@@ -42,9 +44,12 @@ public boolean isValidSudoku(char[][] board) {
4244
record[board[i][j] - '.']++;
4345
}
4446

45-
if (!check(record)) { // 如是检查失败
47+
// 如是检查失败
48+
if (!check(record)) {
4649
return false;
47-
} else { // 检查成功重置棋盘
50+
}
51+
// 检查成功重置棋盘
52+
else {
4853
reset(record);
4954
}
5055
}
@@ -83,11 +88,7 @@ public boolean isValidSudoku(char[][] board) {
8388
}
8489

8590
private void reset(int[] a) {
86-
for (int i = 0; i < a.length; i++) {
87-
a[i] = 0;
88-
}
89-
90-
91+
Arrays.fill(a, 0);
9192
}
9293

9394
/**

[042][Trapping Rain Water]/src/Solution.java

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,33 @@ public int trap(int[] height) {
1111
return trap4(height);
1212
}
1313

14+
/**
15+
* <pre>
16+
* 对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是min(max_left,max_right) - height。所以,
17+
* 1. 从左往右扫描一遍,对于每个柱子,求取左边最大值;
18+
* 2. 从右往左扫描一遍,对于每个柱子,求最大右值;
19+
* 3. 再扫描一遍,把每个柱子的面积并累加。
20+
* </pre>
21+
*
22+
* @param height
23+
* @return
24+
*/
1425
public int trap1(int[] height) {
1526
int ans = 0;
1627
int size = height.length;
1728
for (int i = 1; i < size - 1; i++) {
1829
int maxLeft = 0;
1930
int maxRight = 0;
20-
for (int j = i; j >= 0; j--) { //Search the left part for max bar size
31+
// 找此柱左边最高的柱子
32+
for (int j = i - 1; j >= 0; j--) {
2133
maxLeft = Math.max(maxLeft, height[j]);
2234
}
23-
for (int j = i; j < size; j++) { //Search the right part for max bar size
35+
// 找此柱子右边最高的柱子
36+
for (int j = i + 2; j < size; j++) {
2437
maxRight = Math.max(maxRight, height[j]);
2538
}
2639

27-
// TODO 原理是什么?
40+
// Math.min(maxLeft, maxRight) - height[i] 此柱子可以容纳的水
2841
ans += Math.min(maxLeft, maxRight) - height[i];
2942
}
3043
return ans;
@@ -39,15 +52,13 @@ int trap2(int[] height) {
3952
int[] leftMax = new int[size];
4053
int[] rightMax = new int[size];
4154

42-
leftMax[0] = height[0];
43-
for (int i = 1; i < size; i++) {
55+
56+
// 对于每个柱子求左右最大值,并保存起来
57+
for (int i = 1; i < size - 1; i++) {
4458
leftMax[i] = Math.max(height[i], leftMax[i - 1]);
59+
rightMax[size - i - 1] = Math.max(height[size - i], rightMax[size - i]);
4560
}
4661

47-
rightMax[size - 1] = height[size - 1];
48-
for (int i = size - 2; i >= 0; i--) {
49-
rightMax[i] = Math.max(height[i], rightMax[i + 1]);
50-
}
5162

5263
for (int i = 1; i < size - 1; i++) {
5364
ans += Math.min(leftMax[i], rightMax[i]) - height[i];

0 commit comments

Comments
 (0)