Algorithm ---> [map using] seeking the most harmonious sequence

Explanation

  • Harmony array means the difference between the maximum and minimum values ​​of the elements in an array exactly 1.

  • Now, given an array of integers, you need to find the length of the longest sequence of harmony in all possible sub-sequences.

  • Input: [1,3,2,2,5,2,3,7]
    Output: 5
    Reason: Harmony longest array is: [3,2,2,2,3].


Thinking

  • Create a map statistics for the number of values ​​in the array, and the value appears
  • Create a max, to save the maximum number of emerging
  • Traversing the map, look for the number of times the current value is greater than 1 that appears in the map
var findLHS = function (nums) {
    let map = new Map();
    for (let i = 0; i < nums.length; i++) {
        if (map.has(nums[i])) {
            map.set(nums[i], map.get(nums[i]) + 1)
        } else {
            map.set(nums[i], 1);
        }
    }
    let max = 0;
    for(let [key , value] of map){
        if(map.has(key +1)){
            max = Math.max(max, map.get(key +1) + map.get(key));
        }
    }
    return max
};

to sum up

  • map initializationconst map = new Map()
  • Map to determine whether it contains an elementmap.has(xxx)
  • Gets the value of the mapmap.get(xxx)
  • Set the value mapmap.set(xxx, yyy)
  • map traversalfor(let [key, value] of map) { xxx }
Published 177 original articles · won praise 22 · views 20000 +

Guess you like

Origin blog.csdn.net/piano9425/article/details/103557803
Recommended