mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #1620 from PanYuHaa/master
0463.岛屿的周长增加go解法;1356.根据数字二进制下 1 的数目排序增加go语言的解法
This commit is contained in:
@ -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
|
||||
|
@ -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
|
||||
|
Reference in New Issue
Block a user