1, collections,

An unordered and unique data structure In fact, we can think of a set as an array with neither repeating elements nor any notion of order

  • Js can use ES6SetSyntax to represent sets.
  • Common operations of sets: de-duplication, finding intersection, and determining whether an element is in the set

2. Use collections in JS

// Declare a collection
const list = new Set([1.2.3.4.5])

// Take advantage of the collection's unordered and uniquely deduplicated nature
const arr = [1.2.1.3.3.2]
const arr2 = [...new Set(arr)] / / [1, 2, 3]

// Determine if the element is in the set
const set = new Set(arr)
set.has(4) // false

/ / intersection
const set1 = new Set([1.2.3.4])
const set2 = new Set([11.2.23.3])
const result = new Set([...set1].filter(item= > set2.has(item)))
/ / [2, 3]
Copy the code

3, the dictionary

Like collections, a dictionary is a data structure that stores unique values, but it is stored as key-value pairs

  • Js can use ES6MapGrammar, to represent dictionaries.
  • Dictionary operations: add or delete key – value pairs.

4. Use dictionaries in JS

const map = new Map(a)/ / to add
map.set('a'.'aa') // { a => aa }
map.set('b'.'bb') // { a => aa, b => bb }
/ / delete
map.delete('a') // { b => bb }
// map.clear() // Delete all
/ / change
map.set('b'.'bb1') // { b => bb1 }
Copy the code

5, leetCode

1. Sum of two numbers

Given an integer array nums and an integer target value target, find the two integers in the array and the target value target and return their array subscripts.

  • You can assume that there is only one answer for each type of input. However, the same element in the array cannot be repeated in the answer.
  • You can return the answers in any order.
/ * * *@param {number[]} nums
 * @param {number} target
 * @return {number[]}* /
/ * * *@param {string} s
 * @return {number}* /
var lengthOfLongestSubstring = function(s) {
    let l = 0; / / pointer to the left
    let res = 0
    // Create a dictionary
    const map = new Map(a);for (let i = 0; i < s.length; i++) {
        // Move the left pointer to the next bit of the repeated string if it encounters a duplicate string
        // The repeated string position cannot be smaller than the left pointer
        if (map.has(s[i]) && map.get(s[i]) >= l) {
            l = map.get(s[i]) + 1
        }
        // Take the current maximum length
        res = Math.max(res, i - l + 1)
        map.set(s[i], i)
    }
    return res
};
Copy the code