我試圖編寫的代碼假設接受一個二維整數數組,對每行進行排序,然後找到行之間的最大公用數。我遇到了如何返回整數類型的問題。查找最大公共數
目前我無法找到一種方法來取得我創建的行數組並返回它作爲整數。同樣,我知道從測試中總共會有3行,但列數量是未知的。
import java.util.Arrays;
public class FindCommon {
/*
* @param a 3xN integer array, assume a is not null or empty
* @return the largest common number among a[0], a[1], a[2], null if no common number exists
*/
public static Integer getLargestCommonNumber(int[][] a) {
//Check if array is empty
if (a == null || a.length == 0){
return 0;
}
//Initialize
int [] Row1 = a[0];
int [] Row2 = a[1];
int [] Row3 = a[2];
Arrays.sort(a);
int i = 0, j = 0, k = 0;
// Iterate through three arrays while all arrays have elements
while (i < Row1.length && j < Row2.length && k < Row3.length)
{
if (Row1[i] > Row2[j] && Row2[j] > Row3[k]){
System.out.print(Row1[i]+" ");
int max = Row1[i];
}
else if (Row2[i] > Row1[j] && Row2[j] > Row3[k]){
System.out.print(Row2[i]+" ");
int max = Row2[i];
}
else if (Row3[i] > Row1[j] && Row3[j] > Row2[k]){
int max = Row3[i];
}
}
}
}
我有我用來解決這個問題的測試代碼。
import org.junit.Assert;
import org.junit.Test;
public class FindCommonTest {
@Test
public void testGetLargestCommonNumber1() {
int[][] a = {{54, 41, 43, 55, 63}, {25, 40, 48, 12, 89}, {20, 19, 90, 94, 52}};
Integer result = FindCommon.getLargestCommonNumber(a);
Assert.assertNull(result);
}
@Test
public void testGetLargestCommonNumber2() {
int[][] a = {{53, 41, 43, 55, 63}, {41, 25, 48, 12, 54}, {91, 19, 90, 54, 41}};
Integer result = FindCommon.getLargestCommonNumber(a);
Assert.assertEquals(41, (int) result);
}
@Test
public void testGetLargestCommonNumber3() {
int[][] a = {{54, 41, 43, 55, 63}, {25, 41, 48, 12, 54}, {41, 19, 90, 54, 94}};
Integer result = FindCommon.getLargestCommonNumber(a);
Assert.assertEquals(54, (int) result);
}
}
我不太明白你的問題。你不知道如何從一個方法返回一個整數,或者你問如何從一個方法返回多個整數? –