This article is participating in the “Java Theme Month – Java Brush questions punch card”, see the activity link for details

Topic describes

This is 1748 on LeetCode. The sum of the only elements is easy.

Tag: “simulation”, “hash table”

Give you an integer array nums. The only elements in the array are those that occur “exactly once.”

Return the sum of the unique elements in NUMS.

Example 1:

Input: nums = [1,2,3,2] output: 4 explanation: the unique elements are [1,3] and are 4.Copy the code

Example 2:

Input: nums = [1,1,1,1,1] output: 0 explanation: there are no unique elements and the sum is 0.Copy the code

Example 3:

Input: nums = [1,2,3,4,5] output: 15 explanation: the unique elements are [1,2,3,4,5], and are 15.Copy the code

Tip:

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

simulation

A simulation problem, directly use hash table or array to store the number of elements can be.

For some problems that are given a range of element data, it is recommended to use data for statistics, which is shorter for the Java language.

For no given element data range, or for a large data range, hash tables are used.

Code:

class Solution {
    public int sumOfUnique(int[] nums) {
        int[] cnt = new int[110];
        for (int i : nums) cnt[i]++;
        int ans = 0;
        for (int i = 0; i < 110; i++) {
            if (cnt[i] == 1) ans += i;
        }
        returnans; }}Copy the code
  • Time complexity: O(n)O(n)O(n)
  • Space complexity: O(n)O(n)O(n)

The last

This is the No.1748 of our “Brush through LeetCode” series of articles. The series started on 2021/01/01.

In this series of articles, in addition to explaining how to solve the problem, I will also present the most concise code possible. If a general solution is involved, the corresponding code template will also be used.

In order to facilitate the students to debug and submit the code on the computer, I set up the relevant warehouse: github.com/SharingSour…

In the repository, you’ll see links to the series of articles, the corresponding code for the series of articles, the LeetCode source links, and other preferred solutions.