※ 引述《sustainer123 (caster )》之銘言:
: 1051. Height Checker
: 給定一數列heights 我們期待heights是一非遞減數列
: 看解答好像能把時間複雜度降到n 等等研究一下
思路:
用bucket
然後這題用HashMap沒特別省時間
還會耗空間資源
這種小範圍的還是直接用Vec比較好
但我都寫了
:(
Code:
use std::collections::HashMap;
impl Solution {
pub fn height_checker(heights: Vec<i32>) -> i32 {
let mut heights_freq= HashMap::new();
for &num in &heights {
*heights_freq.entry(num).or_insert(0) += 1;
}
let mut index = 0;
let mut result = 0;
for height in 0..=100 {
if let Some(&count) = heights_freq.get(&(height as i32)) {
for _ in 0..count {
if heights[index] != height as i32 {
result +=1;
}
index += 1;
}
}
}
result
}
}