我正在使用Java,我试图仅使用递归函数从2d数组中获取所有不同的值,而不使用HashSet ArrayList等。, 这些值仅为[0-9] 即:
{{4,2,2,1,4},{4,4,3,1,4},{1,1,4,2,1},{1,4,0,2,2},{4,1,4,1,1}}; -> Returns 5 (Because 4,2,3,1,0)
{{4,6,2,1,4},{4,4,3,1,4},{1,1,4,2,1},{1,4,0,2,2},{4,1,4,1,1}}; -> Returns 6 (Because 4,2,3,1,0,6)
{{4,4,4,4,4}}; -> Returns 1 (4)
我尝试了什么:
public static int numOfColors(int[][] map) {
int colors = 0;
if (map == null || map.length == 0) {
return colors;
} else {
int[] subArr = map[map.length - 1];
for (int i = 0; i < subArr.length; i++) {
int j = i + 1;
for (; j < subArr.length; j++) {
if (subArr[i] == subArr[j]) {
break;
}
}
if (j == subArr.length) {
int k = 0;
for (; k < map.length - 1; k++) {
for (int l = 0; l < map[k].length; l++) {
if (subArr[i] == map[k][l]) {
continue;
}
}
}
if (k == map.length - 1) {
colors++;
}
}
}
int[][] dest = new int[map.length - 1][];
System.arraycopy(map, 0, dest, 0, map.length - 1);
colors += numOfColors(dest);
return colors;
}
}
但这对我没有用,哪里有误?
答案 0 :(得分:2)
递归在这里没有多大意义。只需使用一个简单的数组作为存储,并计算不同值的实例,如果你知道范围(0-9)那么一个简单的int []就足够了。
这应该可以解决问题:
public static int numOfColors(int[][] map){
int[] storage = new int[10];
//iterate through all the values
for(int i = 0; i<map.length; i++){
for(int j = 0; j<map[0].length; j++){
//will throw an Exception if an entry in map is not 0-9
//you might want to check for that
storage[map[i][j]]++;
}
}
int colors = 0;
//now check which values exist.
for(int i = 0; i<storage.length; i++){
if(storage[i] != 0) colors++;
}
return colors;
}
答案 1 :(得分:1)
正如@Cash Lo已经提到的那样,你需要某种存储空间。所以你的算法可能看起来像:
@Test
public void numOfColorsTest() {
int[][] map = new int[][] {{4,2,2,1,4},{4,4,3,1,4},{1,1,4,2,1},{1,4,0,2,2},{4,1,4,1,1}};
System.out.println(String.format("numOfColors: %s", numOfColors(map, new int[0], map.length-1)));
map = new int[][] {{4,6,2,1,4},{4,4,3,1,4},{1,1,4,2,1},{1,4,0,2,2},{4,1,4,1,1}};
System.out.println(String.format("numOfColors: %s", numOfColors(map, new int[0], map.length-1)));
map = new int[][] {{4,4,4,4,4}};
System.out.println(String.format("numOfColors: %s", numOfColors(map, new int[0], map.length-1)));
}
public static int numOfColors(int[][] map, int[] collector, int currentPosition) {
int[] result = collector;
if (currentPosition < 0) {
return collector.length;
}
for (int color : map[currentPosition]) {
boolean found = false;
for (int aResult : result) {
if (aResult == color) {
found = true;
break;
}
}
if (!found) {
int[] newResult = new int[result.length + 1];
System.arraycopy(result, 0, newResult, 0, result.length);
newResult[newResult.length - 1] = color;
result = newResult;
}
}
return numOfColors(map, result, currentPosition-1);
}
答案 2 :(得分:0)
我知道这不是答案,但您应该始终考虑您的解决方案是否有意义。
在我看来,使用递归是非常糟糕的主意,因为:
请考虑以下代码。它完全符合您的需求:
Integer[][] array = {{4,2,2,1,4},{4,4,3,1,4},{1,1,4,2,1},{1,4,0,2,2},{4,1,4,1,1}};
int size = Arrays.stream(array)
.flatMap(Arrays::stream)
.collect(Collectors.toSet())
.size();
System.out.println("size = " + size);
如果你故意在这种情况下使用递归,我唯一能推荐的就是测试驱动开发。编写算法并同时进行测试。