int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}不重复的取最大值并且每一次取到最大值就从数组中移除并打印,直到结束,
时间: 2023-08-19 18:00:06 浏览: 52
你可以使用以下代码来实现每次取到不重复最大值并从数组中移除并打印,直到结束:
```java
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
while (arr.length > 0) {
int max = Integer.MIN_VALUE;
int maxIndex = -1;
// 找到当前数组中的最大值和其索引
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
maxIndex = i;
}
}
// 移除最大值并打印
System.out.println("当前最大值: " + max);
arr = removeElement(arr, maxIndex);
}
}
// 移除指定索引位置的元素并返回新数组
public static int[] removeElement(int[] arr, int index) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if (i != index) {
list.add(arr[i]);
}
}
int[] newArr = new int[list.size()];
for (int i = 0; i < newArr.length; i++) {
newArr[i] = list.get(i);
}
return newArr;
}
}
```
这段代码会在每次迭代中找到数组中的最大值及其索引,然后将其移除并打印。移除元素的过程是通过创建一个新的ArrayList来存储除了最大值元素之外的其他元素,然后将ArrayList转换回原始的int数组。这样,每次迭代都会移除已经取过的最大值,直到数组为空为止。
输出结果会依次打印每次取到的最大值。