LeetCode 1748. Sum of Unique Elements

原题链接在这里:https://leetcode.com/problems/sum-of-unique-elements/description/

题目:

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

题解:

Have a map to maintain num to its frequency.

Iterate the map again to pick the entry with frequency as 1 and accumulate the key.

Time Complexity: O(n). n = nums.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int sumOfUnique(int[] nums) {
 3         HashMap<Integer, Integer> hm = new HashMap<>();
 4         for(int num : nums){
 5             hm.put(num, hm.getOrDefault(num, 0) + 1);
 6         }
 7         
 8         int res = 0;
 9         for(Map.Entry<Integer, Integer> entry : hm.entrySet()){
10             if(entry.getValue() == 1){
11                 res += entry.getKey();
12             }
13         }
14         
15         return res;
16     }
17 }

 

posted @ 2024-06-04 11:54  Dylan_Java_NYC  阅读(2)  评论(0编辑  收藏  举报