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

[pull] master from youngyangyang04:master #358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 3 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Oct 5, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat(1356 数字二进制1排序): 使用Go内置排序函数
  • Loading branch information
aFlyBird0 committed Sep 28, 2023
commit 546d3b601a2be997855a0d9da2c5af567ebbfaa5
41 changes: 17 additions & 24 deletions problems/1356.根据数字二进制下1的数目排序.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -171,36 +171,29 @@ class Solution:

```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
}
}
// 是否arr[i]<=arr[j]
// 先比较1的数量,后比较值本身
cmp := func(i, j int) bool {
c1, c2 := bitCount(arr[i]), bitCount(arr[j])
if c1 == c2 {
return arr[i] <= arr[j]
}
return c1 <= c2
}
return arr
}

func isCmp(a, b int) bool {
bitA := bitCount(a)
bitB := bitCount(b)
if bitA == bitB {
return a > b
} else {
return bitA > bitB
}
// 调用库函数
// 第一个参数是待排序切片,第二个是第i位是否小于第j位的函数
sort.Slice(arr, cmp)

return arr
}

func bitCount(n int) int {
count := 0
for n != 0 {
n &= (n-1) // 清除最低位的1
func bitCount(num int) (count int) {
for num != 0 {
num &= num-1 // 每次运算将最右侧的1变成0
count++
}

return count
}
```
Expand Down

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