java一个一维数组有2个相同最小值和最大值,怎么输出及其位置?
答案:3 悬赏:40
解决时间 2021-02-27 01:35
- 提问者网友:夕夏残阳落幕
- 2021-02-26 20:41
比如int [] a={12,11,134,2,21,42,2,111,23,134,54,62},怎么输出2和134,以及他们对应的角标
最佳答案
- 二级知识专家网友:一池湖水
- 2021-02-26 20:50
遍历计算,赋值。
public static void main(String[] args){
int [] a={12,11,134,2,21,42,2,111,23,134,54,62};
int tempmin = 0, tempmax = 0;
List<Integer> minIndex = new ArrayList<Integer>(), maxIndex = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++)
{
if (i == 0)
{
//这里假设了第一位数字就是最大值和最小值
tempmin = a[0];
tempmax = a[0];
minIndex.add(0);
maxIndex.add(0);
}
else
{
int temp = a[i];
if (temp < tempmin)
{
tempmin = temp;
minIndex.clear();
minIndex.add(i);
}
else if (temp == tempmin)
{
minIndex.add(i);
}
if (temp > tempmax)
{
tempmax = temp;
maxIndex.clear();
maxIndex.add(i);
}
else if (temp == tempmax)
{
maxIndex.add(i);
}
}
}
System.out.println("最小值下标为:" + minIndex + " 最大值下标为:" + maxIndex);
}
快试试啊,正确答案呢····
怎么看不到你的追问呢?
public static void main(String[] args){
int [] a={12,11,134,2,21,42,2,111,23,134,54,62};
int tempmin = 0, tempmax = 0;
List<Integer> minIndex = new ArrayList<Integer>(), maxIndex = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++)
{
if (i == 0)
{
//这里假设了第一位数字就是最大值和最小值
tempmin = a[0];
tempmax = a[0];
minIndex.add(0);
maxIndex.add(0);
}
else
{
int temp = a[i];
if (temp < tempmin)
{
tempmin = temp;
minIndex.clear();
minIndex.add(i);
}
else if (temp == tempmin)
{
minIndex.add(i);
}
if (temp > tempmax)
{
tempmax = temp;
maxIndex.clear();
maxIndex.add(i);
}
else if (temp == tempmax)
{
maxIndex.add(i);
}
}
}
System.out.println("最小值下标为:" + minIndex + " 最大值下标为:" + maxIndex);
}
快试试啊,正确答案呢····
怎么看不到你的追问呢?
全部回答
- 1楼网友:woshuo
- 2021-02-26 21:51
先排序,找出最小和最大值,在和原数组数据进行比较,这样很容易得到数组下标。
- 2楼网友:我的任性你不懂
- 2021-02-26 21:16
public static void main(String[] args) {
List<Integer> arr = new ArrayList<Integer>();
arr.add(12);
arr.add(11);
arr.add(134);
arr.add(2);
arr.add(21);
arr.add(42);
arr.add(2);
arr.add(用面向对象思想。
public class Test
{
int num;
int index;
Test(int num, int index)
{
this.num = num;
this.index = index;
}
public static void main(String[] args)
{
int[] a = { 12, 11, 134, 2, 21, 42, 2, import java.util.*;
public class Test {
public static void main(String[] args) {
int[] num={12,11,134,2,21,42,2,import java.util.arrays;
public class test1 {
public static void main(string[] args) {
int[] ary = {23, 43, 21, 67, 33, 89, 70};
arrays.sort(ary);
int max = ary[ary.length-1];
int min = ary[0];
system.out.println("最大值是:" + max);
system.out.println("最小值是:" + min);
system.out.println("差值是:" + (max - min));
}
}
运行结果
最大值是:89
最小值是:21
差值是:68
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯