[LeetCode] 1748. Sum of Unique Elements
阿新 • • 發佈:2022-02-06
You are given an integer arraynums
. The unique elements of an array are the elements that appearexactly oncein the array.
Returnthesumof all the unique elements ofnums
.
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
唯一元素的和。
給你一個整數陣列nums。陣列中唯一元素是那些只出現恰好一次的元素。
請你返回 nums中唯一元素的 和。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/sum-of-unique-elements
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
思路是雜湊表 + 記錄狀態,掃描一遍即可。注意 input 給的範圍是 1 - 100,所以這裡我們用一個長度為 101 的 map 陣列記錄每個元素是否出現過
因為 Java 陣列建立後預設值是 0,所以沒有出現過我們記為 0
數字如果第一次出現,我們把 map 裡這個數字標記為 1 並且將這個數值累加到結果裡
如果遇到一個已經是 1 的數字,把 map 裡這個數字標記為 2 並將這個數值從結果裡減去,這樣下次我們再遇到 2 的時候直接跳過不處理即可
時間O(n)
空間O(1) - map 陣列長度只有 101
Java實現
1 class Solution { 2 public intsumOfUnique(int[] nums) { 3 int res = 0; 4 int[] map = new int[101]; 5 for (int num : nums) { 6 if (map[num] == 0) { 7 res += num; 8 map[num] = 1; 9 } else if (map[num] == 1) { 10 res -= num; 11 map[num] = 2; 12 } 13 } 14 return res; 15 } 16 }