[英]A program that computes the smallest element in an array which is larger than given int x. (using recursion)
[英]Program that prints the smallest element greater than x in a given unsorted array A[]
我必須使用遞歸的程序,其輸入是正數和正數x的數組A。 程序應打印大於x的A的最小元素。 如果不存在這樣的元素,則程序應打印-1。 例如,如果A = [1、3、5、3、6、5]且x = 3,則程序應打印5。
我已經通過常規方法解決了該程序,而沒有使用遞歸,如下所示:
FindNum(A[ ], x) {
result = -1;
for (i = 0; i < len(A[ ]); i++) {
if (A[i] > x AND (result > A[i] OR result == -1)) {
result = A[i];
}
}
print (result);
}
我已經相應地在python中實現了此偽代碼,並且工作正常。 現在,我必須使用遞歸操作。 我已經嘗試這樣做,但是我不確定如何正確實現它:
FindNum(A [ ], x) {
i = len(A[]) - 1;
result = -1;
while (i > 0 {
if (A[i] > x AND (result > A[i] OR result == -1)) {
result = A[i];
i--;
}
FindNum(A[i], x);
}
print result;
}
具有簡單條件的Python遞歸函數(無單行)。 它找到列表尾部的結果,然后嘗試使用當前元素對其進行改進
def mingreater(A, x):
if 0 == len(A):
return -1
result = mingreater(A[1:], x)
if result > 0:
if A[0] > x:
return min(result, A[0])
else:
if A[0] > x:
return A[0]
return result
沒有特定於Python的切片:
def mingreater(A, x, idx):
if idx == len(A):
return -1
result = mingreater(A, x, idx + 1)
if result > 0:
if A[idx] > x:
return min(result, A[idx])
else:
if A[idx] > x:
return A[idx]
return result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.