topic:
Gives you an integer array nums. The only elements in the array are those that only appear exactly once.
Please return the sum of the only elements in nums.
Example 1:
Input: nums = [1,2,3,2]
Output: 4
Explanation: The only element is [1,3] and the sum is 4.
Example 2:Input: nums = [1,1,1,1,1]
Output: 0
Explanation: There is no unique element, and the sum is 0.
Example 3:Input: nums = [1,2,3,4,5]
Output: 15
Explanation: The only element is [1,2,3,4,5], and the sum is 15.prompt:
1 <= nums.length <= 100
1 <= nums[i] <= 100
Ideas:
1. Traverse the array for the first time, first count the number of occurrences of each element
2. Traverse the map for the second time and sum
Code:
/**
* @param {number[]} nums
* @return {number}
*/
var sumOfUnique = function (nums) {
let map = new Map(), sum = 0;
nums.forEach(item => {
let count = map.get(item) || 0;
map.set(item, ++count)
});
for(let [key, value] of map) {
if(value === 1) {
sum += key;
}
}
return sum;
};
operation result: