数组中求最大值的方法

(1)for 循环:数组中循环求最大值

var arr=[1,5,9,0,1,-3,-98,100,80];
function fn(){
				var max=arr[0];
				for(var i=0;i<arr.length;i++){
					if(max<arr[i]){
						max=arr[i];
					}
				}return max;
			}
			console.log(fn());
			

(2)三目运算配合reduce求取数组当中最大值

console.log(arr.reduce(function(pre,item,index,arr){return pre>item?pre:item;},arr[0]))

(3)sort();方法求取最大值

function fn2(a,b){
				return b-a;
			}
			var newArr=arr.sort(fn2);
			//console.log(newArr) 打印排序后的新数组
			console.log(newArr.splice(0,1).toString());

(4)循环取数组每一项,拿最大值

var max= arr[0]
			for(var x of arr){
				max=max>x?max:x;
			}
			console.log(max);
			

(5)apply方法解析数组进行传参,求最大值

console.log(Math.max.apply(null,arr));
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用以下代码来求一个数组中最大数出现的次数: ```java public static int getMaxCount(int[] arr) { int max = arr[]; int count = 1; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; count = 1; } else if (arr[i] == max) { count++; } } return count; } ``` 其中,max 表示当前最大值,count 表示最大值出现的次数。我们从数组的第二个元素开始遍历,如果当前元素大于最大值,就更新最大值,并将计数器重置为 1;如果当前元素等于最大值,就将计数器加 1。最后返回计数器的值即可。 ### 回答2: 要用Java写一个求一个数组中最大数出现的次数的程序,你需要遵循以下步骤: 1. 声明一个整数类型的数组,并初始化数组元素。 2. 定义一个整数类型的变量maxCount,并将其初始化为0,用于存储最大数出现的次数。 3. 定义一个整数类型的变量maxNum,并将其初始化为数组中的第一个元素,用于存储最大数。 4. 使用for循环遍历数组中的每个元素。 5. 在循环中,使用if条件语句判断当前元素是否大于maxNum。如果是,则将maxNum更新为当前元素,并将maxCount重置为1。 6. 如果当前元素等于maxNum,则将maxCount加1。 7. 完成循环后,maxCount的值即为最大数出现的次数。 以下是一个示例代码: ```java public class Main { public static void main(String[] args) { int[] array = {2, 5, 3, 5, 7, 5}; // 声明并初始化数组 int maxCount = 0; // 最大数出现的次数 int maxNum = array[0]; // 最大数 for (int i = 0; i < array.length; i++) { if (array[i] > maxNum) { // 如果当前元素大于最大数 maxNum = array[i]; // 更新最大数 maxCount = 1; // 重置出现次数 } else if (array[i] == maxNum) { // 如果当前元素等于最大数 maxCount++; // 出现次数加1 } } System.out.println("最大数为:" + maxNum); System.out.println("最大数出现的次数为:" + maxCount); } } ``` 以上代码输出结果为: ``` 最大数为:7 最大数出现的次数为:3 ``` 这表示数组中最大的数为7,而且它出现了3次。 ### 回答3: 如果要用Java编写一个求一个数组中最大数出现次数的方法,可以按照以下步骤进行: 1. 定义一个方法,名称为 getMaxCount,参数为一个整型数组。 2. 声明一个变量 max 用于存储数组中的最大数,初始值设为数组的第一个元素。 3. 声明一个变量 count 用于计算最大数的出现次数,初始值设为 0。 4. 使用 for 循环遍历数组的每个元素,从第二个元素开始比较,如果当前元素大于 max,则更新 max 的值,并将 count 置为 1。 5. 如果当前元素等于 max,则将 count 的值加 1。 6. 循环结束后,最大数的出现次数就存储在 count 中。 7. 返回 count 的值作为结果。 以下是示例代码: ```java public class Main { public static void main(String[] args) { int[] array = {1, 2, 3, 3, 4, 4, 4}; int maxCount = getMaxCount(array); System.out.println("最大数出现的次数:" + maxCount); } public static int getMaxCount(int[] array) { int max = array[0]; int count = 0; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; count = 1; } else if (array[i] == max) { count++; } } return count; } } ``` 以上代码会输出最大数出现的次数为 3。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值