1356. 根据数字二进制下 1 的数目排序

This commit is contained in:
li_chx 2026-02-25 15:35:37 +08:00
parent 0f894b29a8
commit 495075eef2
Signed by: li_chx
GPG Key ID: 70D4985BB8180E92
1 changed files with 15 additions and 25 deletions

View File

@ -1,36 +1,26 @@
use std::cmp::Ordering;
struct Solution; struct Solution;
mod arr; mod arr;
impl Solution { impl Solution {
pub fn sp(s : &str)-> String{ pub fn sort_by_bits(arr: Vec<i32>) -> Vec<i32> {
if s.len() <= 2 { let mut arr= arr.iter().map(|&x| ->(i32,i32){
return s.to_string(); (x,x.count_ones() as i32)
}).collect::<Vec<(i32,i32)>>();
arr.sort_unstable_by(|a,b|-> Ordering {
let res = a.1.cmp(&b.1);
match res {
Ordering::Equal => a.0.cmp(&b.0),
_ => res,
} }
let mut left = 0; });
let mut cnt = 0; arr.iter().map(|&(x,_)| x).collect()
let sb = s.as_bytes();
let mut arr = Vec::new();
for i in 0..s.len() {
if sb[i] == b'1' {
cnt += 1;
}else {
cnt -= 1;
}
if cnt == 0 {
arr.push(format!("1{}0",Self::sp(&s[left + 1 .. i])));
left = i + 1;
}
}
arr.sort_unstable_by(|a,b| b.cmp(a));
arr.join("")
}
pub fn make_largest_special(s: String) -> String {
Self::sp(s.as_str())
} }
} }
fn main() { fn main() {
let result = Solution::make_largest_special( let result = Solution::sort_by_bits(
"101101101010101010001010101010110011011010001100".to_string(), vec![0,1,2,3,4,5,6,7,8]
); );
println!("{:?}", result); println!("{:?}", result);
} }