From a605d75ec6d24efb68a03ff7e669de937d6a5891 Mon Sep 17 00:00:00 2001 From: SwaggyP <1352164869@qq.com> Date: Sat, 3 Sep 2022 10:52:35 +0800 Subject: [PATCH 1/2] =?UTF-8?q?0463.=E5=B2=9B=E5=B1=BF=E7=9A=84=E5=91=A8?= =?UTF-8?q?=E9=95=BF=E5=A2=9E=E5=8A=A0go=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0463.岛屿的周长增加go解法 --- problems/0463.岛屿的周长.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0463.岛屿的周长.md b/problems/0463.岛屿的周长.md index 3dc69f20..a881cd7c 100644 --- a/problems/0463.岛屿的周长.md +++ b/problems/0463.岛屿的周长.md @@ -179,6 +179,25 @@ class Solution: ``` Go: +```go +func islandPerimeter(grid [][]int) int { + m, n := len(grid), len(grid[0]) + res := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == 1 { + res += 4 + // 上下左右四个方向 + if i > 0 && grid[i-1][j] == 1 {res--} // 上边有岛屿 + if i < m-1 && grid[i+1][j] == 1 {res--} // 下边有岛屿 + if j > 0 && grid[i][j-1] == 1 {res--} // 左边有岛屿 + if j < n-1 && grid[i][j+1] == 1 {res--} // 右边有岛屿 + } + } + } + return res +} +``` JavaScript: ```javascript From d0d693ffae17369a54a99cd5040f904037b3b78a Mon Sep 17 00:00:00 2001 From: SwaggyP <1352164869@qq.com> Date: Sun, 4 Sep 2022 10:21:43 +0800 Subject: [PATCH 2/2] =?UTF-8?q?1356.=20=E6=A0=B9=E6=8D=AE=E6=95=B0?= =?UTF-8?q?=E5=AD=97=E4=BA=8C=E8=BF=9B=E5=88=B6=E4=B8=8B=201=20=E7=9A=84?= =?UTF-8?q?=E6=95=B0=E7=9B=AE=E6=8E=92=E5=BA=8F=20=E5=A2=9E=E5=8A=A0go?= =?UTF-8?q?=E8=AF=AD=E8=A8=80=E7=9A=84=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1356. 根据数字二进制下 1 的数目排序 增加go语言的解法 --- ...据数字二进制下1的数目排序.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/1356.根据数字二进制下1的数目排序.md b/problems/1356.根据数字二进制下1的数目排序.md index 5ca73607..e97748cb 100644 --- a/problems/1356.根据数字二进制下1的数目排序.md +++ b/problems/1356.根据数字二进制下1的数目排序.md @@ -170,6 +170,39 @@ class Solution: ## Go ```go +func sortByBits(arr []int) []int { + var tmp int + for i := 0; i < len(arr); i++ { + for j := i+1; j < len(arr); j++ { + // 冒泡排序的手法,但是排序的规则从比大小变成了比位运算1的个数 + if isCmp(arr[i], arr[j]) { + tmp = arr[i] + arr[i] = arr[j] + arr[j] = tmp + } + } + } + return arr +} + +func isCmp(a, b int) bool { + bitA := bitCount(a) + bitB := bitCount(b) + if bitA == bitB { + return a > b + } else { + return bitA > bitB + } +} + +func bitCount(n int) int { + count := 0 + for n != 0 { + n &= (n-1) // 清除最低位的1 + count++ + } + return count +} ``` ## JavaScript