“This is the 11th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

preface

Today’s topic is simple, and the type of the question is 884. The uncommon words in the two sentences are very similar, with the same optimization idea

A daily topic

1748. The sum of the only elements is simple

  • Give you an integer array nums. The only elements in an array are those that appear exactly once.

  • Return the sum of the unique elements in NUMS.

Example 1:

Enter: nums = [1.2.3.2] output:4Explanation: The only element is [1.3], and for4Copy the code

Example 2:

Enter: nums = [1.1.1.1.1] output:0Explanation: There are no unique elements, and are0Copy the code

Example 3:

Enter: nums = [1.2.3.4.5] output:15Explanation: The only element is [1.2.3.4.5], and for15Copy the code

Tip:

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

Answer key

Hash table

Use a hash table to keep the number of occurrences of each element, and then run through the hash table again, adding up the numbers that only occur once, to get the answer you need

/ * * *@param {number[]} nums
 * @return {number}* /
var sumOfUnique = function (nums) {
  const map = new Map(a);let ans = 0;
  for (const num of nums) {
    map.set(num, (map.get(num) || 0) + 1);
  }
  for (const [key ,val] of map.entries()) {
    if (val == 1) { ans += key; }}return ans;
};
Copy the code

Optimization – One traversal

So the hash table above is going to go through the array once and the hash table once, so we’re going to go through it twice, and then we’re going to optimize it, and we’re going to go through it once.

884. This is similar to the unusual words in the two sentences. We have used this method before:

Leetcode brush record -884. Uncommon words in two sentences

We just need to walk through the array, add all the undiscovered words to a hash table and set two conditions:

  1. The number that occurs has a value of 1 and is added to the total number of answers
  2. Any number that occurs more than twice has a value of 2 and is subtracted from the total number of answers
/ * * *@param {number[]} nums
 * @return {number}* /
var sumOfUnique = function(nums) {
  let ans = 0;
  const map = new Map(a);for (const num of nums) {
      if(! map.has(num)) { ans += num; map.set(num,1);
      } else if (map.get(num) === 1) {
          ans -= num;
          map.set(num, 2); }}return ans;
};
Copy the code