[英]Need to replace the element by the max of the right side elements in an array
I need to replace every element in an array
with the max element that belong to the right side set of elements in that array. 我需要用属于该数组右侧元素集的max元素替换
array
每个元素。 I got a solution with the below code: 我得到了以下代码的解决方案:
let arr1 = [5,0,5,7,9,4,8];
var temp = [];
for (var i = 1; i < arr1.length + 1; i++)
{
if (i !== arr1.length)
{
temp = [...arr1].slice(i);
arr1[i-1] = Math.max(...temp);
}
else
{
arr1[i-1] = arr1[arr1.length - 1];
}
}
console.log(arr1);
Is there any other better solution for solve this? 还有其他更好的解决方案吗? You can see expected output on next sample:
您可以在下一个示例中看到预期的输出:
Input : [5,0,5,7,9,4,8]
Output: [9,9,9,9,8,8,8]
You can use Array.map() . 您可以使用Array.map() 。 Note this approach, also, do not mutates your original array.
请注意,这种方法也不要使原始数组变异。
let arr1 = [5,0,5,7,9,4,8]; let res = arr1.map( (n, idx, arr) => (idx < arr.length-1) ? Math.max(...arr.slice(idx+1)) : n ); console.log(res);
.as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}
Another alternative with O(n)
performance can be approached using Array.reduceRight 可以使用Array.reduceRight实现具有
O(n)
性能的另一种选择
let arr1 = [5,0,5,7,9,4,8]; let max = arr1[arr1.length - 1]; let res = arr1.reduceRight( (acc, n, idx) => (acc[idx] = max, max = Math.max(n, max), acc), [] ); console.log(res);
.as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}
You can improve performance to O(n) (since your current implementation is O(n^2) ) by iterating backwards and keeping track of the max: 您可以通过向后迭代并跟踪max来提高O(n)的性能(因为当前的实现是O(n ^ 2) ):
var arr1 = [5, 0, 5, 7, 9, 4, 8]; var max = arr1[arr1.length - 1]; for (var i = arr1.length - 1; i >= 0; i--) { var curr = arr1[i]; arr1[i] = max; if (curr > max) max = curr; } console.log(arr1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.