java数组除去最大值
时间: 2025-05-09 15:20:11 浏览: 21
### 删除Java数组中的最大值元素
在 Java 中,如果要从数组中移除最大值元素并返回一个新的数组而不影响原始数组,可以通过以下方式实现。首先找到数组中的最大值及其索引位置[^1],然后构建一个不包含该最大值的新数组[^3]。
以下是完整的解决方案:
#### 方法描述
通过遍历数组找出其中的最大值以及其对应的索引位置。接着创建一个新的数组,新数组的长度比原数组少 1,并将除了最大值以外的所有元素复制到新的数组中[^4]。
#### 实现代码
```java
public class RemoveMaxValue {
public static int[] removeMax(int[] arr) {
if (arr == null || arr.length == 0) {
throw new IllegalArgumentException("Array must not be empty");
}
// 找到最大值及其索引
int maxIndex = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
// 创建新数组并将非最大值元素复制进去
int[] result = new int[arr.length - 1];
for (int i = 0, j = 0; i < arr.length; i++) {
if (i != maxIndex) {
result[j++] = arr[i];
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {3, 7, 2, 9, 5};
int[] newArray = removeMax(nums);
System.out.println("Original Array:");
for (int num : nums) {
System.out.print(num + " ");
}
System.out.println("\nNew Array without Max Value:");
for (int num : newArray) {
System.out.print(num + " ");
}
}
}
```
上述代码实现了如下功能:
- 定义了一个 `removeMax` 函数用于删除数组中的最大值。
- 使用循环查找最大值的位置,并将其排除在外生成新数组。
- 原始数组保持不变,仅返回修改后的副本[^5]。
#### 输出示例
假设输入数组为 `{3, 7, 2, 9, 5}`,运行以上程序会得到以下输出:
```
Original Array:
3 7 2 9 5
New Array without Max Value:
3 7 2 5
```
---
阅读全文
相关推荐


















