javascript - Output largest element on the right for each element in an Array -
consider input of arr1 = [4, 6, 3, 9, 11, 5]
i want function takes array input. each element in array, should output first higher value on right.
example output : 4 - 6 ; 6 - 9 ; 3 - 9 ; 9 - 11 , 11 - -1 , 5 - -1
requirement : want implement without using nested loops.
for (i = 0,k = arr1.length;i< k;i ++){ var val = false; for(j=i+1;j<k;j++){ while(arr1[i] < arr1[j] ){ console.log( arr1[i] + " --" + arr1[j]); val = true; break; } if(val){break;} } if( !val){ console.log( arr1[i] + " --" +" -1"); } }
here's example of how it. idea iterate through array, @ every element after 1 you're looking @ until find 1 greater. greater element (or -1 default) pushed second array storage.
var arr1 = [4, 6, 3, 9, 11, 5]; var arr2 = []; (var i=0;i<arr1.length;i++) { var biggernumber = -1; (var j=i+1;j<arr1.length;j++) { if (arr1[j]>arr1[i]) { biggernumber = arr1[j]; break; } } arr2.push(biggernumber); } //output: for(var i=0;i<arr1.length;i++) { console.log(arr1[i]+" -- "+arr2[i]); }
updated answer:
var arr1 = [4, 6, 3, 9, 11, 5]; var stack=[]; arr1.foreach(function(i){ if (stack.length==0 || i<=stack[stack.length-1]) { stack.push(i); } else { while(stack.length>0 && i>stack[stack.length-1]) { console.log(i); stack.pop(); } stack.push(i); } }); stack.foreach(function(){console.log(-1);});
why it's better: inner loop performs arr1.length
operations total, it's still running in o(n). how implement without nested loops still have no idea.
Comments
Post a Comment