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 546d3b6

Browse files
feat(1356 数字二进制1排序): 使用Go内置排序函数
1 parent 5117a28 commit 546d3b6

File tree

1 file changed

+17
-24
lines changed

1 file changed

+17
-24
lines changed

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

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -171,36 +171,29 @@ class Solution:
171171

172172
```go
173173
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-
}
174+
// 是否arr[i]<=arr[j]
175+
// 先比较1的数量,后比较值本身
176+
cmp := func(i, j int) bool {
177+
c1, c2 := bitCount(arr[i]), bitCount(arr[j])
178+
if c1 == c2 {
179+
return arr[i] <= arr[j]
180+
}
181+
return c1 <= c2
184182
}
185-
return arr
186-
}
187183

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-
}
184+
// 调用库函数
185+
// 第一个参数是待排序切片,第二个是第i位是否小于第j位的函数
186+
sort.Slice(arr, cmp)
187+
188+
return arr
196189
}
197190

198-
func bitCount(n int) int {
199-
count := 0
200-
for n != 0 {
201-
n &= (n-1) // 清除最低位的1
191+
func bitCount(num int) (count int) {
192+
for num != 0 {
193+
num &= num-1 // 每次运算将最右侧的1变成0
202194
count++
203195
}
196+
204197
return count
205198
}
206199
```

0 commit comments

Comments
(0)

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