c ++遞歸算法數的計數
Given an array of length N and an integer x, you need to find and return the last index of integer x present in the array. Return -1 if it is not present in the array. Last index means - if x is present multiple times in the array, return the index at which x comes last in the array.
給定長度為N和整數x的數組,您需要查找并返回數組中存在的整數x的最后一個索引。 如果數組中不存在,則返回-1。 Last index表示-如果x在數組中多次出現,則返回x在數組中最后出現的索引。
You should start traversing your array from 0, not from (N - 1). Do this recursively. Indexing in the array starts from 0.
您應該從0開始遍歷數組,而不是從(N-1)開始遍歷數組。 遞歸執行此操作。 數組中的索引從0開始。
Input Format:
輸入格式:
Line 1 : An Integer N i.e. size of array
第1行:整數N,即數組的大小
Line 2 : N integers which are elements of the array, separated by spaces
第2行: N個整數,它們是數組的元素,以空格分隔
Line 3 : Integer x
第3行:整數x
Output Format: last index or -1
輸出格式:最后一個索引或-1
Constraints: 1 <= N <= 10^3
限制條件: 1 <= N <= 10 ^ 3
Example
例
Input:
4
9 8 10 8
8
Output:
3
Description:
描述:
Here, we have to find the last occurrence of x. Therefore, in this example the last occurrence of 8 happens in index 3, and hence the output is 3.
在這里,我們必須找到x的最后一次出現。 因此,在此示例中,最后一次出現8發生在索引3中,因此輸出為3。
Algorithm:
算法:
Step 1: To solve this using recursion, make a recursion function with inputs, and a variable currIndex to traverse the input array.
步驟1:要使用遞歸解決此問題,請使用輸入創建遞歸函數,并使用變量currIndex遍歷輸入數組。
Step2: Base Case:- If currIndex == size of the input array, return -1, i.e element not found.
步驟2:基本情況:-如果currIndex ==輸入數組的大小,則返回-1,即找不到元素。
Step3: Take input of next recursion call ,withcurrIndex incremented by 1 , in a variable ‘index’.
步驟3:在變量“ index”中,獲取下一個遞歸調用的輸入,其currIndex遞增1。
Step 4:
If(index == -1 && input[currIndex] == x)
Return currIndex
Else
Return index;
第4步:
If(索引== -1 &&輸入[currIndex] == x)
返回currIndex
其他
返回索引;
C ++源代碼/功能: (C++ Source Code/Function:)
#include<bits/stdc++.h>
using namespace std;
int lastIndex(int input[], int size, int x, int currIndex){
if(currIndex== size){
return -1;
}
int index = lastIndex(input,size,x,currIndex+1);
if(index == -1 && input[currIndex] == x){
return currIndex;
}
else{
return index;
}
}
int main(){
int input[] = {9,8,10,8};
int x = 8;
int size = 4;
cout<<lastIndex(input,size,x,0);
return 0;
}
Output
輸出量
3
翻譯自: https://www.includehelp.com/cpp-programs/find-last-occurrence-of-a-number-using-recursion-in-an-array.aspx
c ++遞歸算法數的計數