【问题标题】:How do you get 2nd highest and the lowest numbers in Javascript using arrays如何使用数组在 Javascript 中获得第二高和最低的数字
【发布时间】:2018-01-18 06:30:02
【问题描述】:

如何在 javascript 中获得第二高和第二低的数字? 不使用 js 中的排序或任何其他功能。 我实际上得到了最高和最低,但我真的不知道如何解决才能获得第二个数字。这是我的代码

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript">

function myFunction(){
 var numone = document.getElementById("num1").value;
 var numtwo = document.getElementById("num2").value;
 var numthree = document.getElementById("num3").value;
 var numfour = document.getElementById("num4").value;
 var numfive = document.getElementById("num5").value;
  
 var array = [numone,numtwo,numthree,numfour,numfive];


var largest= 0;

for (i=0; i<=array.length;i++){
    if (array[i]>largest) {
        var largest=array[i];
    }
    
}
    document.getElementById("largest").value = largest;

var smallest=array[0];

for (i=0; i<array.length; i++){
 if(array[i]<smallest){
  var smallest=array[i];
}
    document.getElementById("lowest").value = smallest;
}

}

</script>
</head>
<body>

<input type="number" id="num1">
<input type="number" id="num2">
<input type="number" id="num3">
<input type="number" id="num4">
<input type="number" id="num5">

<button type="button" onclick="myFunction()" class="btn btn-default">SUBMIT</button>
<input type="text" id="largest" disabled>
<input type="text" id="lowest" disabled>
<script type="text/javascript">
myFunction();
</script>
</body>
</html>

【问题讨论】:

标签: javascript


【解决方案1】:

你可以通过以下方式做到这一点

let arr = [1, 2, 3, 4, 5];
let maxx = arr[0], idxMaxx = 0;
let minn = arr[0], idxMinn = 0;
 
for(let i=0; i<arr.length; i++){
	if(arr[i] > maxx){
		maxx = arr[i];
		idxMaxx = i;
	}
	if(arr[i] < minn){
		minn = arr[i];
		idxMinn = i;
	}
}
 
let Secondmaxx = -1, idxSecondMaxx = -1;
let Secondminn = -1, idxSecondMinn = -1;
 
for(let i=0; i<arr.length; i++){
	if(arr[i] > Secondmaxx && i!= idxMaxx){
		Secondmaxx = arr[i];
		idxSecondMaxx = i;
	}
	if(Secondminn == -1 && i != idxMinn){
		Secondminn = arr[i];
		idxSecondMinn = i;
	}
	if(arr[i] < Secondminn){
		Secondminn = arr[i];
		idxSecondMinn = i;
	}
}
 
console.log(Secondmaxx, idxSecondMaxx);
console.log(Secondminn, idxSecondMinn);

时间复杂度 O(n) 其中 n 是数组中元素的数量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2016-08-09
    相关资源
    最近更新 更多