LeetCode Brush Questions | Sum of Unique Elements

Subject:
Give 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.

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

Idea 1: Build a hash table, loop twice, the first loop puts the numbers in the nums array into the hash table, and the second loop adds the items with 0 in the hash table and outputs the result ans ;

int SumOnlyOne(std::vector<int>& nums)
{
    
    
	int brr[101] = {
    
     0 };
	int ans = 0;
	for (int i = 0; i < nums.size(); i++)
	{
    
    
		brr[nums[i]]++;//构建哈希表
	}
	for (int j = 0; j < nums.size(); j++)
	{
    
    
		if (brr[nums[j]] == 1)
		{
    
    
			ans  += nums[j];
		}
	}
	return ans;
}

Idea 2: Hash table, a for loop, add from the beginning, if the number is 0, add to the total, and subtract from the total if the number is 1, until the traversal is completed, the output result ans;

int SumOnlyOne1(std::vector<int>& arr)
{
    
    
	int brr[101] = {
    
     0 };
	int ans = 0;
	for (int i = 0; i < arr.size(); ++i)
	{
    
    
		if (brr[arr[i]] == 0)
			ans += arr[i];
		else if (brr[arr[i]] == 1)
			ans -= arr[i];
		brr[arr[i]]++;
	}
	return ans;
}

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/115284676