给定一个整数数组,找到任意两个元素之间的绝对差小于或等于
的最长子数组_a = [1,1,2,2,4,4,5,5,5]_
有两个满足条件的子数组:[1,1,2,2]和[4,4,5,5,5]。最大长度子数组有 5 个元素。
在下面的编辑器中完成pickingnumbers函数。
pickingnumbers 有以下参数:
第一行包含一个整数n,即数组a的大小。
第二行包含 n 个空格分隔的整数,每个整数都是 a[i].
function pickingNumbers(a) { // Create an array to store frequency of each element in the input array let frequency = new Array(100).fill(0); // Count frequency of each element for (let i = 0; i < a.length; i++) { frequency[a[i]]++; } // Initialize a variable to store the maximum length of subarray found let maxLength = 0; // Traverse through frequency array to find the longest subarray for (let i = 1; i < frequency.length; i++) { // The length of a valid subarray is the sum of the frequency of // the current element and the previous element maxLength = Math.max(maxLength, frequency[i] + frequency[i - 1]); } return maxLength; }
以上就是选择数字 - HakerRank 解决方案 - Javascript的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号