给定一个二进制数组 nums
, 找到含有相同数量的 0
和 1
的最长连续子数组,并返回该子数组的长度。
/** * @param {number[]} nums * @return {number} */ const findMaxLength = (nums) => { let maxLength = 0; const map = new Map(); let counter = 0; map.set(counter, -1); const n = nums.length; for (let i = 0; i < n; i++) { const num = nums[i]; if (num == 1) { counter++; } else { counter--; } if (map.has(counter)) { const prevIndex = map.get(counter); maxLength = Math.max(maxLength, i - prevIndex); } else { map.set(counter, i); } } return maxLength; };
标签:map,const,nums,counter,连续,数组,maxLength From: https://www.cnblogs.com/zhenjianyu/p/17106429.html