Leetcode 1748. Sum of Unique Elements
Given an integer array nums
, return the sum of all the unique elements of nums
. An element of nums
is unique if it appears exactly once in the array.
-1000
to 1000
, but confirm this if possible.nums
.To solve this problem, we can follow these steps:
Here’s the implementation in C++:
#include <iostream>
#include <vector>
#include <unordered_map>
int sumOfUnique(std::vector<int>& nums) {
std::unordered_map<int, int> freqMap;
// Populate frequency map
for(const int& num : nums) {
freqMap[num]++;
}
int sum = 0;
// Sum up elements with frequency exactly 1
for(const auto& entry : freqMap) {
if(entry.second == 1) {
sum += entry.first;
}
}
return sum;
}
int main() {
std::vector<int> nums = {1, 2, 3, 2};
std::cout << "Sum of unique elements: " << sumOfUnique(nums) << std::endl;
return 0;
}
nums
:
nums
.Feel free to run the provided code with different input cases to verify its correctness. If you have any additional questions or need further clarifications, please let me know!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?