Return to school: the fourth question-1748. The sum of the only elements

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 = [1,2,3,2]
输出:4
解释:唯一元素为 [1,3] ,和为 4 。
示例 2:

输入:nums = [1,1,1,1,1]
输出:0
解释:没有唯一元素,和为 0 。
示例 3 :

输入:nums = [1,2,3,4,5]
输出:15
解释:唯一元素为 [1,2,3,4,5] ,和为 15 。
 

提示:

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

answer:

Just use the hash table idea directly.

Code:

int sumOfUnique(int* nums, int numsSize){
    
    
    int hash[101]={
    
    0};
    int temp = 0;
    for(int i=0;i<numsSize;i++)
    {
    
    
        hash[nums[i]]++;
    }
    for(int i=1;i<=100;i++)
    {
    
    
        if(hash[i]==1)
        {
    
    
            temp=temp+i;
        }
    }
    return temp;
}

Guess you like

Origin blog.csdn.net/xiangguang_fight/article/details/114400572