Java 实现线性时间内求数组最大最小值 (3n/2-2 比较次数)
import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = scanner.nextInt(); }
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i += 2) {
if (nums[i] > nums[i+1]) {
max = Math.max(max, nums[i]);
min = Math.min(min, nums[i+1]);
} else {
max = Math.max(max, nums[i+1]);
min = Math.min(min, nums[i]);
}
}
System.out.println('最大值:' + max);
System.out.println('最小值:' + min);
}
}
原文地址: https://www.cveoy.top/t/topic/hN9 著作权归作者所有。请勿转载和采集!