Skip to content

Latest commit

 

History

History
128 lines (92 loc) · 3.01 KB

1748.md

File metadata and controls

128 lines (92 loc) · 3.01 KB
title description keywords
1748. 唯一元素的和
LeetCode 1748. 唯一元素的和题解,Sum of Unique Elements,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
1748. 唯一元素的和
唯一元素的和
Sum of Unique Elements
解题思路
数组
哈希表
计数

1748. 唯一元素的和

🟢 Easy  🔖  数组 哈希表 计数  🔗 力扣 LeetCode

题目

You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.

Return _the sum of all the unique elements of _nums.

Example 1:

Input: nums = [1,2,3,2]

Output: 4

Explanation: The unique elements are [1,3], and the sum is 4.

Example 2:

Input: nums = [1,1,1,1,1]

Output: 0

Explanation: There are no unique elements, and the sum is 0.

Example 3:

Input: nums = [1,2,3,4,5]

Output: 15

Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.

Constraints:

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

题目大意

给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。

请你返回 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

解题思路

题目要求计算数组中只出现一次的元素之和,通过统计每个数字的出现次数,过滤出只出现一次的数字,然后累加即可。

  1. 统计频次

    • 使用 Map 数据结构记录数组中每个数字的出现次数。
    • 遍历数组,逐一将每个数字的频次存入 Map 中。
  2. 筛选唯一元素

    • 使用 filter 遍历 Map 的键值对,只保留频次为 1 的数字。
  3. 求和

    • 使用 reduce 将筛选出的数字累加,并返回累加值。

复杂度分析

  • 时间复杂度O(n),频次统计,筛选和累加操作分别遍历数组一次。
  • 空间复杂度O(n),使用了 Map 存储频次。

代码

/**
 * @param {number[]} nums
 * @return {number}
 */
var sumOfUnique = function (nums) {
	let freq = new Map();
	for (let num of nums) {
		freq.set(num, (freq.get(num) || 0) + 1); // 更新频次
	}
	return Array.from(freq)
		.filter(([key, count]) => count === 1) // 筛选频次为1的数字
		.reduce((acc, [key]) => acc + key, 0); // 累加键值
};