Java 找到两个具有最大和的数组元素的方法
两个数组元素的最大和意味着我们需要找到两个最大的数组元素,这最终会给出可能的最大和。
在本文中,我们将看到如何在Java中找到两个元素的最大和。
为了向您展示一些示例
示例1
假设我们有以下数组
[10, 2, 3, -5, 99, 12, 0, -1]
在此数组中,最大的元素是99,第二大的元素是12。
最大和= 99 + 12
因此,该数组中两个元素的最大和为111。
示例2
假设我们有以下数组
[556, 10, 259, 874, 123, 453, -96, -54, -2369]
在此数组中,最大的元素是874,第二大的元素是556。
最大和= 874+556
因此,该数组中两个元素的最大和为1430。
示例3
假设我们有以下数组
[55, 10, 29, 74, 12, 45, 6, 5, 269]
在此数组中,最大的元素是269,第二大的元素是74。
最大和= 269+74
因此,该数组中两个元素的最大和为343。
步骤
步骤1
步骤1 - 使用for循环找到数组中最大和第二大的元素。
步骤2 - 计算它们的和。
步骤3 - 打印和。
步骤2
步骤1 - 对数组元素进行排序。
步骤2 - 取数组的最后一个和倒数第二个元素。
步骤3 - 计算它们的和。
步骤4 - 打印和。
语法
要对数组进行排序,我们需要使用java.util包中的Arrays类的sort()方法。
使用该方法按升序对任何数组进行排序的语法如下:
Arrays.sort(array_name);
其中,’array_name’是指你想要排序的数组。
多种方法
我们提供了不同的解决方案。
- 使用for循环找到最大的和
-
使用Arrays.sort找到最大的和
让我们逐一看看程序及其输出。
方法1:使用for循环
在这种方法中,我们使用for循环遍历数组元素,找出最大和第二大的元素。这两个元素将给出最大的和。
示例
public class Main {
public static void main(String[] args) {
// The array elements
int arr[] = { 10, 2, 3, -5, 99, 12, 0, -1 };
// Storing the first element in both variables
int first = arr[0], second = arr[0];
// For loop to iterate the elements from 1 to n
// to find the first largest element
for (int i = 0; i < arr.length; i++) {
// If array element is larger than current largest element, then swap
if (arr[i] > first)
first = arr[i];
}
// For loop to iterate the elements from 1 to n
// to find the second largest element
for (int i = 0; i < arr.length; i++) {
// If array element is larger than current largest element and not equals to
// largest element, then swap
if (arr[i] > second && arr[i] != first)
second = arr[i];
}
// Print the sum
System.out.println("Largest sum = " + (first + second));
System.out.println("The elements are " + first + " and " + second);
}
}
输出
Largest sum = 111
The elements are 99 and 12
方法2:使用Arrays.sort进行排序
在这种方法中,我们使用Arrays.sort()方法对数组进行排序。然后我们取倒数第一个和倒数第二个元素。由于数组已经排序,这两个元素将得到最大的和。
示例
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// The array elements
int arr[] = { 10, 2, 3, -5, 99, 12, 0, -1 };
// Sort the array using the sort method from array class
Arrays.sort(arr);
// Storing the last element as largest and second last element as second largest
int first = arr[arr.length - 1], second = arr[arr.length - 2];
// Print the maximum sum
System.out.println("Maximum sum = " + (first + second));
System.out.println("The elements are " + first + " and " + second);
}
}
输出
Maximum sum = 104
The elements are 99 and 12
在本文中,我们探讨了在Java中找到数组中具有最大和的两个元素的不同方法。