g1701_1800.s1748_sum_of_unique_elements.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g1701_1800.s1748_sum_of_unique_elements;
// #Easy #Array #Hash_Table #Counting #2022_04_30_Time_2_ms_(54.08%)_Space_42_MB_(38.95%)
import java.util.HashMap;
import java.util.Map;
/**
* 1748 - Sum of Unique Elements\.
*
* Easy
*
* 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`
**/
public class Solution {
public int sumOfUnique(int[] nums) {
Map map = new HashMap<>();
int sum = 0;
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
for (Map.Entry entry : map.entrySet()) {
if (entry.getValue() == 1) {
sum += entry.getKey();
}
}
return sum;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy