Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1113c71

Browse files
Merge pull request youngyangyang04#1620 from PanYuHaa/master
0463.岛屿的周长增加go解法;1356.根据数字二进制下 1 的数目排序增加go语言的解法
2 parents db079ab + d0d693f commit 1113c71

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

‎problems/0463.岛屿的周长.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,25 @@ class Solution:
179179
```
180180

181181
Go:
182+
```go
183+
func islandPerimeter(grid [][]int) int {
184+
m, n := len(grid), len(grid[0])
185+
res := 0
186+
for i := 0; i < m; i++ {
187+
for j := 0; j < n; j++ {
188+
if grid[i][j] == 1 {
189+
res += 4
190+
// 上下左右四个方向
191+
if i > 0 && grid[i-1][j] == 1 {res--} // 上边有岛屿
192+
if i < m-1 && grid[i+1][j] == 1 {res--} // 下边有岛屿
193+
if j > 0 && grid[i][j-1] == 1 {res--} // 左边有岛屿
194+
if j < n-1 && grid[i][j+1] == 1 {res--} // 右边有岛屿
195+
}
196+
}
197+
}
198+
return res
199+
}
200+
```
182201

183202
JavaScript:
184203
```javascript

‎problems/1356.根据数字二进制下1的数目排序.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,39 @@ class Solution:
170170
## Go
171171

172172
```go
173+
func sortByBits(arr []int) []int {
174+
var tmp int
175+
for i := 0; i < len(arr); i++ {
176+
for j := i+1; j < len(arr); j++ {
177+
// 冒泡排序的手法,但是排序的规则从比大小变成了比位运算1的个数
178+
if isCmp(arr[i], arr[j]) {
179+
tmp = arr[i]
180+
arr[i] = arr[j]
181+
arr[j] = tmp
182+
}
183+
}
184+
}
185+
return arr
186+
}
187+
188+
func isCmp(a, b int) bool {
189+
bitA := bitCount(a)
190+
bitB := bitCount(b)
191+
if bitA == bitB {
192+
return a > b
193+
} else {
194+
return bitA > bitB
195+
}
196+
}
197+
198+
func bitCount(n int) int {
199+
count := 0
200+
for n != 0 {
201+
n &= (n-1) // 清除最低位的1
202+
count++
203+
}
204+
return count
205+
}
173206
```
174207

175208
## JavaScript

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /