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 initialization
const map = new Map()
- Map to determine whether it contains an element
map.has(xxx)
- Gets the value of the map
map.get(xxx)
- Set the value map
map.set(xxx, yyy)
- map traversal
for(let [key, value] of map) { xxx }