Skip to content

Commit 0201191

Browse files
authored
Added solution for 1748
1 parent 7124722 commit 0201191

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

01748. Sum of Unique Elements.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
use std::collections::HashMap;
2+
3+
impl Solution {
4+
// Keep count of instances of each number inside the vector. If it is counted first time, add it to the sum. If it is counted a second time, subtract it back from the sum since it need not be counted and it was added earlier. For all subsequent times a number is counted, keep counting it but ignore it from the sum
5+
pub fn sum_of_unique(nums: Vec<i32>) -> i32 {
6+
let mut sum = 0;
7+
8+
// Count instances of each element
9+
let mut map = HashMap::new();
10+
for num in &nums {
11+
let count = map.entry(num).or_insert(0);
12+
*count += 1;
13+
14+
if *count == 1 {
15+
sum += num;
16+
}
17+
18+
if *count == 2 {
19+
sum -= num;
20+
}
21+
}
22+
23+
return sum;
24+
}
25+
}

0 commit comments

Comments
 (0)