Re: [閒聊] 每日leetcode

作者: yam276 ('_')   2024-06-11 15:29:57
※ 引述《sustainer123 (caster )》之銘言:
: https://leetcode.com/problems/relative-sort-array
: 1122. Relative Sort Array
: 給定兩數列arr1與arr2 arr2的元素不重復且皆存在於arr1
: 請依照arr2的順序排列arr1的元素
: 假設有元素不在arr2 請遞增排序
思路:
先用HashMap整理次數
照arr2出現順序放進result vec
然後選剩的孩子們sort後放後面
太苦了 不被需要的粉絲
Code:
use std::collections::HashMap;
impl Solution {
pub fn relative_sort_array(arr1: Vec<i32>, mut arr2: Vec<i32>) -> Vec<i32>
{
let mut arr1_hash = HashMap::new();
for &num in &arr1 {
*arr1_hash.entry(num).or_insert(0)+=1;
}
let mut result = Vec::new();
for &num in &arr2 {
if let Some(&count) = arr1_hash.get(&num){
for _ in 0..count {
result.push(num);
}
arr1_hash.remove(&num);
}
}
let mut rest_arr1 = Vec::new();
for (&num, &count) in &arr1_hash {
for _ in 0..count {
rest_arr1.push(num);
}
}
rest_arr1.sort();
result.extend(rest_arr1);
result
}
}
作者: SecondRun (雨夜琴聲)   2024-06-11 15:33:00
大師
作者: yam276 ('_')   2024-06-11 15:35:00
感覺我脫褲子放屁 我哭了

Links booklink

Contact Us: admin [ a t ] ucptt.com