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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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