ARTS

Algorithm: 每周至少做一道LeetCode算法题
Review: 阅读并点评至少一篇英文技术文章
Tip: 学习至少一个技术技巧
Share: 分享一篇有观点和思考的技术文章

Algorithm

岛屿数量–给定一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。

示例 1:

1
2
3
4
5
6
7
输入:
11110
11010
11000
00000

输出: 1

示例 2:

1
2
3
4
5
6
7
输入:
11000
11000
00100
00011

输出: 3

使用队列和广度优先搜索(BFS)

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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

class Pair<T1, T2> {

private T1 fst;

private T2 snd;

public Pair() {
super();
}

public Pair(T1 fst, T2 snd) {
super();
this.fst = fst;
this.snd = snd;
}

public static <T1, T2> Pair<T1, T2> of(T1 fst, T2 snd) {
return new Pair<>(fst, snd);
}

public T1 getFst() {
return fst;
}

public void setFst(T1 fst) {
this.fst = fst;
}

public T2 getSnd() {
return snd;
}

public void setSnd(T2 snd) {
this.snd = snd;
}

}


class Solution {
public int numIslands(char[][] grid) {

int islandCnt = 0;

for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
char cur = grid[i][j];

if (cur == '0') {
continue;
}

Queue<String> islands = new LinkedList<>();
Queue<Pair<Integer, Integer>> positions = new LinkedList<>();

islands.add(String.valueOf(cur));
positions.add(new Pair<Integer, Integer>(i, j));
grid[i][j] = '0';

islandCnt++;

int row = 0;
int col = 0;

while (!islands.isEmpty()) {

islands.remove();
Pair<Integer, Integer> position = positions.remove();
row = position.getFst();
col = position.getSnd();

// 上
if (row - 1 >= 0 && grid[row - 1][col] != '0') {
islands.add(String.valueOf(grid[row - 1][col]));
positions.add(new Pair<Integer, Integer>(row - 1, col));

grid[row - 1][col] = '0';
}

// 左
if (col - 1 >= 0 && grid[row][col - 1] != '0') {
islands.add(String.valueOf(grid[row][col - 1]));
positions.add(new Pair<Integer, Integer>(row, col - 1));

grid[row][col - 1] = '0';
}

// 下
if (row + 2 <= grid.length && grid[row + 1][col] != '0') {
islands.add(String.valueOf(grid[row + 1][col]));
positions.add(new Pair<Integer, Integer>(row + 1, col));

grid[row + 1][col] = '0';
}

// 右
if (col + 2 <= grid[0].length && grid[row][col + 1] != '0') {
islands.add(String.valueOf(grid[row][col + 1]));
positions.add(new Pair<Integer, Integer>(row, col + 1));

grid[row][col + 1] = '0';
}
}

}
}

return islandCnt;
}
}

Review

Why the perfect lambda expression is just one line

总结

  简短的lambda表达式支持代码的可读性,这是使用函数式编程的主要好处之一。
  避免使用多行lambda表达式。

Tips

    JavaScript 在两数运算时会出现精度问题。
我司的品牌商后台在提现的时候前端需要将提现金额乘以10000传给后台,但是偶尔会出现比如品牌商提现5378.44 * 10000 = 53784399.99999999。
这种数据提交给第三方支付那边会被截取成5378.43,这样我们就多替品牌商出了1分钱,久而久之也挺多的(滑稽)。
所以需要前端使用金钱类库来避免这种精度丢失,后台也对值进行100取余,有余数就不入库,这样就避免这种问题。

Share

那些年,我们见过的Java服务端“问题” – 高德技术