public int minimum(int arr[]) {
if (arr == null || arr.length == 0)
throw new IllegalArgumentException();
if (arr.length == 1)
return arr[0];
int min = minimum(Arrays.copyOfRange(arr, 1, arr.length));
return arr[0] < min ? arr[0] : min;
}
但严格来说,这是一项学术活动——“不要在家里尝试”
# 2 楼答案
public static int[] removeElement(int element,int[] original){
int[] n = new int[original.length - 1];
System.arraycopy(original, 0, n, 0, element );
System.arraycopy(original, element+1, n, element, original.length - element-1);
return n;// http://stackoverflow.com/questions/4870188/delete-item-from-array-and-shrink-array
}
public static int [] shift(int[] original){
int[] a = new int[original.length];
for(int k = 1 ; k < original.length;k++){
a[k-1] = original[k];
}
a[original.length-1] = original[0];
return(a);
}
public static int minimum(int[] arr){ //Process of elimination
if(arr.length==1){ //Base Case
return(arr[0]);
}
if(arr[0]>=arr[1]){// reduction step
return(minimum(removeElement(0,arr)));
}else{ // tread water
return(minimum(shift(arr)));
}
}// There is always a better way but this sould satisfy your teacher.
public int min(int[] n) {
if (n.length > 1) {
int a = n[0];
int b = n[1];
int[] newN = new int[n.length - 1];
for (int i = 0; i < newN.length; i++) {
if (i == 0)
newN[i] = a < b ? a : b;
else
newN[i] = n[i + 1];
}
return min(newN);
}
return n[0];
}
# 5 楼答案
public static int min(int[] n) {
if(n.length == 1)//base case
return(n[0]);
int a = n.length%2 == 0 ? 0:1; //Awesome sauce syntax http://www.cafeaulait.org/course/week2/43.html
int[] r =new int[n.length/2 + a]; // reduce by a factor of 2 each iteration
for(int k = 0 ; k < n.length/2 + a ; k++){ //While copying to a smaller array you might as well make comparisons.
r[k] = n[k]<=n[n.length-k-1] ? n[k] : n[n.length-k-1];//compare the beginning and end of your array, take the smaller of the two.
} //In the case that you have an odd number of elements the middle is always copied trough to the next iteration
return(min(r));//This is where the recursion happens.
} // There is always a better way but this should satisfy your teacher.
# 1 楼答案
您必须将较小的数组依次传递给下一次迭代:
但严格来说,这是一项学术活动——“不要在家里尝试”
# 2 楼答案
给Pratik Popat一张赞成票,因为他抄袭了我平庸的逻辑
# 3 楼答案
其中的诀窍是尝试以递归的方式定义问题,也就是说,在定义中使用操作本身以及不使用的“基本情况”。例如,在本例中,考虑“数组中的最小值”是什么:
所以您有了基本情况(大小为1的数组)和递归。这应该足够你继续下去了
# 4 楼答案
请尝试以下代码:
概念:当数组中只有一个元素时,从数组中删除较大的值并返回min
# 5 楼答案