1356. 根据数字二进制下 1 的数目排序
This commit is contained in:
parent
0f894b29a8
commit
495075eef2
40
src/main.rs
40
src/main.rs
|
|
@ -1,36 +1,26 @@
|
|||
use std::cmp::Ordering;
|
||||
|
||||
struct Solution;
|
||||
mod arr;
|
||||
|
||||
impl Solution {
|
||||
pub fn sp(s : &str)-> String{
|
||||
if s.len() <= 2 {
|
||||
return s.to_string();
|
||||
pub fn sort_by_bits(arr: Vec<i32>) -> Vec<i32> {
|
||||
let mut arr= arr.iter().map(|&x| ->(i32,i32){
|
||||
(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;
|
||||
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())
|
||||
});
|
||||
arr.iter().map(|&(x,_)| x).collect()
|
||||
}
|
||||
}
|
||||
fn main() {
|
||||
let result = Solution::make_largest_special(
|
||||
"101101101010101010001010101010110011011010001100".to_string(),
|
||||
let result = Solution::sort_by_bits(
|
||||
vec![0,1,2,3,4,5,6,7,8]
|
||||
);
|
||||
println!("{:?}", result);
|
||||
}
|
||||
Loading…
Reference in New Issue