面接問題の収集(20)(配列の最大値と二次最大値をとる)
1496 ワード
public class GetMax {
public static void main(String[] args) {
int[] nums = { 2, 3, 4, 1, 2 };
System.out.println(getMax(nums));
System.out.println(getPerMax(nums));
}
/**
*
*/
public static int getMax(int[] nums) {
int max = Integer.MIN_VALUE;
if (nums == null || nums.length == 0) {
throw new NullPointerException(
"the array is null or length less than 1");
}
max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
/**
*
*/
public static int getPerMax(int[] nums) {
int max = Integer.MIN_VALUE;
int perMax = Integer.MIN_VALUE;
if (nums == null || nums.length < 2) {
throw new NullPointerException(
"the array is null or length less than 2");
}
max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] > perMax && nums[i] < max) {
perMax = nums[i];
}
}
if (max == perMax)
throw new RuntimeException("no secord number.");
return perMax;
}
}