1748. 唯一元素的和题解
题目来源:1748. 唯一元素的和
2022.02.06每日一题
法一:遍历哈希表统计每个数字出现的次数
-
遍历数组,用哈希表统计每个数字出现的次数
-
遍历哈希表,统计只出现一次的数字的和
具体代码以及注释如下
C++代码如下
class Solution {
public:
int sumOfUnique(vector<int> &nums) {
// 统计总和
int res = 0;
// 创建统计的哈希表
unordered_map<int, int> statistics;
// 遍历数组,统计每个数字的个数
for (int num: nums) {
statistics[num]++;
}
// 遍历哈希表,查询 value 值时 1 的 key 值
// 用 res 统计 key 的总和
for (auto &[k, v]: statistics) {
if (v == 1) {
res += k;
}
}
// 返回 key 的总值
return res;
}
};
Java代码如下
class Solution {
public int sumOfUnique(int[] nums) {
// 统计总和
int res = 0;
// 创建统计的哈希表
Map<Integer, Integer> statistics = new HashMap<Integer, Integer>();
// 遍历数组,统计每个数组出现的次数
for (int num : nums) {
statistics.put(num, statistics.getOrDefault(num, 0) + 1);
}
// 遍历哈希表,查询 key、value 值
// 如果 value == 1 则统计值 res 加 key
for (Map.Entry<Integer, Integer> entry : statistics.entrySet()) {
if (entry.getValue() == 1) {
res += entry.getKey();
}
}
// 返回结果 key 的总值
return res;
}
}
时间复杂度O(n)
空间复杂度O(n)
法二:使用哈希表的一次循环
- 遍历数组,使用哈希表统计每个数字出现的次数,并在结果中加上这个数字
- 如果一个数字重复出现(该数字对应的 value 值大于1),则在最后的结果中减去这个数
具体代码以及注释如下
C++代码如下
class Solution {
public:
int sumOfUnique(vector<int> &nums) {
// 统计总和
int res = 0;
// 建立哈希表对数组中的值进行统计
unordered_map<int, int> statistics;
for (int num: nums) {
// 统计每个数字出现的次数
statistics[num]++;
// 如果 num 出现的次数为 1 次则在结果 res 中加上
if (statistics[num] == 1) {
res += num;
}
// 如果一个数字再次出现则再 res 之中减去这个结果
// 若一个数字出现的次数为 2 则在 res 之中减去,
// 为了防止一个数字多次出现(次数大于 2),防止多次减同样一个数字,因此只需要当在 value 等于 2 的时候减一次
else if (statistics[num] == 2) {
res -= num;
}
}
// 返回结果
return res;
}
};
Java代码如下
class Solution {
public int sumOfUnique(int[] nums) {
// 统计总和
int res = 0;
// 建立哈希表对数组中的值进行统计
Map<Integer, Integer> statistics = new HashMap<Integer, Integer>();
for (int num : nums) {
// 统计每个数字出现的次数
statistics.put(num, statistics.getOrDefault(num, 0) + 1);
// 如果 num 出现的次数为 1 次则在结果 res 中加上
if (statistics.get(num) == 1) {
res += num;
}
// 如果一个数字再次出现则再 res 之中减去这个结果
// 若一个数字出现的次数为 2 则在 res 之中减去,
// 为了防止一个数字多次出现(次数大于 2),防止多次减同样一个数字,因此只需要当在 value 等于 2 的时候减一次
else if (statistics.get(num) == 2) {
res -= num;
}
}
// 返回结果
return res;
}
}
时间复杂度O(n)
空间复杂度O(n)