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 @   Dylan_Java_NYC  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2019-06-04 Java LinkedList add vs push
2019-06-04 LeetCode 817. Linked List Components
点击右上角即可分享
微信分享提示