題目
在數字鎮上,有一份名為 nums 的數字清單,其中包含從 0 到 n - 1 的整數。每組數字理應在清單中僅出現一次,然而兩組調皮的數字卻偷偷多出現了一次,使得清單比平時更長。
身為鎮上的偵探,你的任務是找出這兩組狡猾的數字。請回傳一個長度為二的陣列,其中包含這兩組數字(順序不限),讓數字鎮重歸和平。
我的練習
class Solution:
def getSneakyNumbers(self, nums: List[int]) -> List[int]:
sneakyNums: List[int] = []
townSet = set()
for n in nums:
if n in townSet:
sneakyNums.append(n)
if len(sneakyNums) == 2:
break
else:
townSet.add(n)
return sneakyNums
use std::collections::HashSet;
impl Solution {
pub fn get_sneaky_numbers(nums: Vec<i32>) -> Vec<i32> {
let mut sneaky_nums: Vec<i32> = Vec::new();
let mut town_set: HashSet<i32> = HashSet::new();
for &n in &nums {
if town_set.contains(&n) {
sneaky_nums.push(n);
if sneaky_nums.len() == 2 {
break;
}
} else {
town_set.insert(n);
}
}
sneaky_nums
}
}