Leetcode 1748. Sum of Unique Elements
Given an integer array nums
, return the sum of all the unique elements in the array. The unique elements of an array are the elements that appear exactly once in the array.
To solve this problem, we’ll use a HashMap
to count the occurrences of each element. Here’s the step-by-step strategy:
public class SumOfUniqueElements {
public int sumOfUnique(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
// Count occurrences of each element
for (int num : nums) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
// Sum up the unique elements
int sum = 0;
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
if (entry.getValue() == 1) {
sum += entry.getKey();
}
}
return sum;
}
public static void main(String[] args) {
SumOfUniqueElements obj = new SumOfUniqueElements();
int[] nums = {1, 2, 3, 2}; // Example input
System.out.println(obj.sumOfUnique(nums)); // Output should be 1 + 3 = 4
}
}
countMap
. In the worst case, m could be equal to n.HashMap
. In the worst case, if all elements are unique, the size of the HashMap will be equal to n.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?