[英]Returning the lowest even number from a 2D array of positive integers
我无法从二维数组返回最小的偶数,但是如果没有偶数,我需要返回-1
。 现在我认为我的主要部分是如何简单地返回最小的数字,但是我无法从这里开始并获得-1
返回,并检查偶数。
public static int array2DLowestEvenNumber(int[][] nums) {
int min = nums[0][0];
for (int j = 0; j < nums.length; j++) {
for (int i = 0; i < nums[j].length; i++) {
if (nums[j][i] < min) {
min = nums[j][i];
}
}
}
return min;
}
public static void main(String[] args) {
System.out.println(array2DLowestEvenNumber(new int[][]{{8,2},{2,4}}));
System.out.println(array2DLowestEvenNumber(new int[][]{{1,50,102},{4,6,7}}));
}
您可以按如下方式使用流:
public static void main(String[] args) {
int[][] arr1 = {{8, 2}, {2, 4}};
int[][] arr2 = {{1, 50, 102}, {4, 6, 7}};
int[][] arr3 = {{3, 5, 7}, {9, 11, 1}};
System.out.println(lowestEvenNumber(arr1)); // 2
System.out.println(lowestEvenNumber(arr2)); // 4
System.out.println(lowestEvenNumber(arr3)); // -1
}
public static int lowestEvenNumber(int[][] arr) {
return Arrays.stream(arr)
// Stream<int[]> to IntStream
.flatMapToInt(Arrays::stream)
// even numbers
.filter(i -> i % 2 == 0)
// minimum of the array
.min().orElse(-1);
}
您可以使用增强的 for 循环,如下所示:
public static void main(String[] args) {
int[][] arr1 = {{8, 2}, {2, 4}};
int[][] arr2 = {{1, 50, 102}, {4, 6, 7}};
int[][] arr3 = {{9, 11, 1}, {3, 5, 7}};
System.out.println(lowestEvenNumber(arr1)); // 2
System.out.println(lowestEvenNumber(arr2)); // 4
System.out.println(lowestEvenNumber(arr3)); // -1
}
public static int lowestEvenNumber(int[][] arr) {
// the maximum value an integer
// can have is odd = 2147483647
int min = Integer.MAX_VALUE;
// rows of the array
for (int[] row : arr)
// elements of the rows
for (int el : row)
// even number and less than the minimum
if (el % 2 == 0 && el < min)
// new minimum
min = el;
// minimum even number of the array, or -1
return min == Integer.MAX_VALUE ? -1 : min;
}
最直接的解决方案是:
int min = -1;
for (int j = 0; j < nums.length; j++) {
for (int i = 0; i < nums[j].length; i++) {
if(nums[j][i] % 2 == 0) {
if (nums[j][i] < min || min == -1) {
min = nums[j][i];
}
}
}
}
return min;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.