LeetCode 1748. Sum of Unique Elements

Gives you an integer array nums. The only elements in the array are those that appear exactly once.

Please return the sum of the only elements in nums.

1 <= nums.length <= 100
1 <= nums[i] <= 100

Using the element range, use a hash table to record the number of occurrences:

class Solution {
    
    
public:
    int sumOfUnique(vector<int>& nums) {
    
    
        vector<int> ha(100);
        for (int i : nums) {
    
    
            ++ha[i - 1];
        }

        int sum = 0;
        for (int i = 0; i < 100; ++i) {
    
    
            if (1 == ha[i]) {
    
    
                sum += i + 1;
            }
        }

        return sum;
    }
};

Guess you like

Origin blog.csdn.net/tus00000/article/details/114439547
Recommended