LeetCode-Number of occurrences of numbers in the array II

Title description

Problem-solving ideas

  • Use the Map data structure in JS
  • First create the Map data structure, and then traverse sequentially to determine whether the data structure contains the elements of the array, if it does not contain, create a key-value pair, and set the value to 1, if it contains, the value is +1
  • Finally traverse the Map data structure, if the value is 1, then return the corresponding key.

Problem-solving code

var singleNumber = function(nums) {
    
    
    const m = new Map();

    for(let v of nums) {
    
    
        if (m.has(v)) {
    
    
            m.set(v,m.get(v)+1);
        } else {
    
    
            m.set(v,1);
        }
    };
    for (let v of m) {
    
    
        if(v[1] === 1) {
    
    
            return v[0];
        }
    }
};

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/114818338