T1:合并两个排序好的整数数组
import java.util.Arrays;public class MergeSortedArrays {public static int[] mergeArrays(int[] arr1, int[] arr2) {int[] result = new int[arr1.length + arr2.length];int i = 0, j = 0, k = 0;while (i < arr1.length && j < arr2.length) {if (arr1[i] < arr2[j]) {result[k++] = arr1[i++];} else {result[k++] = arr2[j++];}}while (i < arr1.length) {result[k++] = arr1[i++];}while (j < arr2.length) {result[k++] = arr2[j++];}return result;}public static void main(String[] args) {int[] arr1 = {1, 3, 5, 7};int[] arr2 = {2, 4, 6, 8};int[] mergedArray = mergeArrays(arr1, arr2);System.out.println("Merged array: " + Arrays.toString(mergedArray));}
}
T2:找出数组中第二大的数
public class SecondLargestInArray {public static void main(String[] args) {int arr[] = {12, 35, 1, 10, 34, 1};int secondLargest = findSecondLargest(arr);System.out.println("The second largest element is " + secondLargest);}public static int findSecondLargest(int[] arr) {int largest = Integer.MIN_VALUE, secondLargest = Integer.MIN_VALUE;for (int i = 0; i < arr.length; i++) {if (arr[i] > largest) {secondLargest = largest;largest = arr[i];} else if (arr[i] > secondLargest && arr[i] != largest) {secondLargest = arr[i];}}return secondLargest;}
}
public class SecondLargestInArray {
public static void main(String[] args) {
int arr[] = {12, 35, 1, 10, 34, 1};
int secondLargest = findSecondLargest(arr);
System.out.println("The second largest element is " + secondLargest);
}
public static int findSecondLargest(int[] arr) {
int largest = Integer.MIN_VALUE, secondLargest = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
}