Sum of Unique Elements

LeetCode.1748. Sum of Unique Elements 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:

Input: nums = [1,2,3,2]
Output: 4
Explanation: The unique elements are [1,3], and the sum is 4.

给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。

请你返回 nums 中唯一元素的

提示:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

First Solution

public int sumOfUnique(int[] nums) {
    Map<Integer, Integer> map = new HashMap();
    int sum = 0;
    for (int i = 0; i < nums.length; i++) {
        if (map.get(nums[i]) == null) {
            map.put(nums[i], 1);
        }else if(map.get(nums[i]) != null){
            map.put(nums[i],map.get(nums[i])+1);
        }
    }
    for (Integer key:map.keySet()) {
        if(map.get(key)== 1){
            sum += key;
        }
    }
    return sum;
}

Better Solution

只需遍历一次的方法

public int sumOfUnique(int[] nums) {
    int[] counts = new int[101];
    int sum = 0;
    for (int n : nums) {
        if (counts[n]++ == 0) {
            sum += n;
        } else if (counts[n] == 2) {
            sum -= n;
        }
    }
    return sum;
}