我需要找到数组中的最小值,但我想知道如何处理多个结果。假设我的数组包含[1,4,7,5,3,1]
- 我的结果应该是1,1
。有什么想法吗?
double minimum = array1[0]; //sets the first to be the smallest
for (int i = 0; i < array1.length; i++) //goes through your array
{
if (array1[i] < array1[0]) //checks and replaces if necessary
{
minimum = array[i];
}
}
System.out.println( minimum ); //returns the value of the smallest
你的
代码中有一个小错误,你应该将当前值与最小值进行比较,而不是第一个值
double minimum = array1[0]; //sets the first to be the smallest
var minValueCounter = 0;
for (int i = 0; i < array1.length; i++) //goes through your array
{
if (array1[i] < minimum) //checks and replaces if necessary
{
minimum = array[i];
minValueCounter = 1;
}
else if (array1[i] == minimum) //checks and replaces if necessary
{
minValueCounter++;
}
}
一件事可以是按升序对数组进行"排序",然后从一开始就显示值,直到它们相等
Arrays.sort(array1);
ArrayList<Integer> smallestValues = new ArrayList<Integer>();
smallestValues.add(array1[0]);
int i=1;
while (i<array1.length && (array1[i] == array1[i-1])) {
smallestValues.add(array1[i]);
i++;
}
保留另一个变量来计算重复项。如果找到等于当前最小值的值,请递增此计数。请记住在每次最小值更改时重置计数。
我会这样做
int[] a = { 1, 4, 7, 5, 3, 1 };
Arrays.sort(a);
int n = 1;
for (int i = 1; i < a.length && a[i] == a[0]; i++)
n++;
int[] res = Arrays.copyOf(a, n);
如何使用Collections.sort()
我假设您的array1[]
属于double
类型
double array1[] = new double[] { 1, 4, 7, 5, 3, 1 };
ArrayList<Double> al = new ArrayList<Double>();
for (int i = 0; i < array1.length; i++)
al.add(array1[i]);
Collections.sort(al);
System.out.println(al.toString());
输出:
[1.0, 1.0, 3.0, 4.0, 5.0, 7.0]
要打印所有相等的最小值,请使用
for (int i = 0; i < (al.size() - 1); i++) { // why (al.size() - 1), Its better if try to learn yourself
if (Double.compare(al.get(i), al.get(i+1))==0)
System.out.print(""+al.get(i) + "," + al.get(i + 1));
else
break;
}
输出:
1.0,1.0
只是为了好玩,一个没有 for 循环的解决方案:
Integer[] inputA = new Integer[]{1,4,7,5,3,1};
List<Integer> inputL = Arrays.asList(inputA);
Collections.sort(inputL);
int last = Collections.frequency(inputL, Collections.min(inputL));
inputA = Arrays.copyOfRange(inputL.toArray(new Integer[inputL.size()]), 0, last);
System.out.println(Arrays.deepToString(inputA));
输出:
[1, 1]
相关方法APIDOC(全静态):
- 集合#排序
- 集合#频率
- 收藏#分钟
- 数组#复制范围
- 数组#deepToString