Java - 求数组中最大值(个数不确定)及其下标
2018-01-05 14:29
330 查看
利用 Map,遍历一次即可获得数组中最大值的同时,也获得最大值的数组下标。
package com.code.ggsddu; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class ArrayMaxAndIndexes { public static void main(String[] args) { int[] arr0 = {2, 2, 2, 2, 2}; int[] arr1 = {2, 3, 5, 4, 3}; int[] arr2 = {3, 3, 5, 5, 5}; int[] arr3 = {1, 2, 3, 5, 5}; int[] arr4 = {5, 4, 2, 5, 5}; System.out.println(Arrays.toString(arr0)); getMaxValuesAndIndexes(arr0); System.out.println("--------------------"); System.out.println(Arrays.toString(arr1)); getMaxValuesAndIndexes(arr1); System.out.println("--------------------"); System.out.println(Arrays.toString(arr2)); getMaxValuesAndIndexes(arr2); System.out.println("--------------------"); System.out.println(Arrays.toString(arr3)); getMaxValuesAndIndexes(arr3); System.out.println("--------------------"); System.out.println(Arrays.toString(arr4)); getMaxValuesAndIndexes(arr4); } public static void getMaxValuesAndIndexes(int[] arr) { Map<String, Object> map = new HashMap<>(); int max = arr[0]; map.put("indexes", 0); for (int i = 1; i < arr.length; i++) { int temp = arr[i]; if (max == temp) { map.put("indexes", map.get("indexes") + "," + i); } else if (max < temp) { max = temp; map.put("indexes", i); } } System.out.println("max: " + max); System.out.println("indexes: " + map.get("indexes")); String[] indexesArray = map.get("indexes").toString().split(","); System.out.println("indexesArray: " + Arrays.toString(indexesArray)); } }
控制台打印结果:
[2, 2, 2, 2, 2] max: 2 indexes: 0,1,2,3,4 indexesArray: [0, 1, 2, 3, 4] -------------------- [2, 3, 5, 4, 3] max: 5 indexes: 2 indexesArray: [2] -------------------- [3, 3, 5, 5, 5] max: 5 indexes: 2,3,4 indexesArray: [2, 3, 4] -------------------- [1, 2, 3, 5, 5] max: 5 indexes: 3,4 indexesArray: [3, 4] -------------------- [5, 4, 2, 5, 5] max: 5 indexes: 0,3,4 indexesArray: [0, 3, 4] Process finished with exit code 0
相关文章推荐
- JAVA获取数组中最大值及其下标
- 函数fun,其功能是:找出一维整型数组元素中最大的值及其所在的下标,并通过形参传回。数组元素中的值已在主函数中赋予
- 一维静态数组_实例:寻找随机数最大值及其下标(附:源码)
- java 数组中两数之差的最大值 蛮力算法 动态规划及其优化
- Java之给出数组求其最大值位置下标
- java__给定一个非负整数数组,假定你的初始位置为数组第一个下标。 数组中的每个元素代表你在那个位置能够跳跃的最大长度。 请确认你是否能够跳跃到数组的最后一个下标。
- 【C++程序设计】补6.1 输出数组最大值及其下标
- 通过随机数生成办法,向int num[10][10]的数组 中存入数据并找出数组的最大、最小值及其下标。
- 5-8: 输入一个5行、6列的数组,找出该数组中绝对值最大的元素,输出该元素及其两个下标值
- 在一个有8个整数(18,25,7,36,13,2,89,63)的数组中找出其中最大的数及其下标。
- Java 随机生成50个正整数,存放到数组,求出总和,平均值,最大值,最小值
- java获取数组连续相同元素下标
- 连续子数组的最大和(java版)
- js实现求连续子数组的最大和并输出下标
- Java 找数组中与下标相等的元素
- java输入多个数据(不确定),排序,并求最大值
- PHP获取数组最大值下标的方法
- 求子数组的最大值之和并给出子数组的下标
- Java程序:求一个数组中的最大值丶最小值和平均值。