私が書いてみたいコードは、整数の2次元配列を受け取り、各行をソートしてから、行間の最大公約数を見つけることを想定しています。整数型を返す方法に関する問題に取り組んでいます。最大公約数を見つける
現在、私が作成した行配列を取得して整数に戻す方法はありません。同様に、私は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);
}
}
私はあなたの質問をよく理解していません。メソッドから整数を返す方法を知らないのですか、メソッドから複数の整数を返す方法を尋ねていますか? –