Original link: leetcode-cn.com/problems/sh… Original link: juejin.cn/post/684490…

Topic describes

At a length ofAn array ofnumsAll the numbers in theWithin the scope of. Some numbers in the array are repeated, but we don’t know how many are repeated, or how many times each number is repeated. Please find any duplicate number in the array.

Limitations:

Example:

Input: [2, 3, 1, 0, 2, 5, 3] Output: 2 or 3

Subject analysis

For such problems we can use hash table to solve, the specific steps are as follows:

  • Through the arraynumsTo generate theHash table, where the number askey.keyThe number of times the number should appear
  • Traverse theHash tableIf the number of occurrences is greater than1Returns the number directly

The code is as follows:

/** * @param {number[]} nums * @return {number} */
var findRepeatNumber = function(nums) {
    const map = new Map(a)for (const num of nums) {
        const val = map.get(num)
        if (map.has(num)) {
            map.set(num, val + 1)}else {
            map.set(num, 1)}}for (const [key, val] of map) {
        if (val > 1) {
            return key
        }
    }
};
Copy the code

To optimize the

For the above code, in fact, we only need to loop once, here is the code directly put, should be easy to understand:

/** * @param {number[]} nums * @return {number} */
var findRepeatNumber = function(nums) {
    const map = new Map(a)for (const num of nums) {
        const val = map.get(num)
        if (map.has(num)) {
            return num
        }
        map.set(num, 1)}};Copy the code

Search “Tony’s front-end cram school” and follow my wechat official account, so you can receive my latest articles in the first time.