c ++递归算法数的计数
Given an array of length N and an integer x, you need to find and return the first index of integer x present in the array. Return -1 if it is not present in the array. First index means, the index of first occurrence of x in the input array. Do this recursively. Indexing in the array starts from 0.
给定长度为N的数组和整数x ,您需要找到并返回数组中存在的整数x的第一个索引。 如果数组中不存在,则返回-1 。 First index表示输入数组中x首次出现的索引。 递归执行此操作。 数组中的索引从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: first index or -1
输出格式:第一个索引或-1
Constraints: 1 <= N <= 10^3
限制条件: 1 <= N <= 10 ^ 3
Example
例
Input:
4
9 8 10 8
8
Output:
1
Description:
描述:
Here, we have to find the first occurrence of x. Therefore in this example the first occurrence of 8 happens in index 1, and hence the output is 1.
在这里,我们必须找到x的第一次出现。 因此,在此示例中,第一次出现8发生在索引1中,因此输出为1。
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遍历输入数组。
Step 2: Base Case: If currIndex == size of the input array, return -1, i.e element not found.
步骤2:基本情况:如果currIndex ==输入数组的大小 ,则返回-1,即找不到元素。
Step 3: If x == input[currIndex], then return currIndex.
步骤3:如果x == input [currIndex] ,则返回currIndex 。
Step 4: else return the next call of recursive function with currIndex incremented.
步骤4:否则,返回递归函数currIndex递增的下一个调用。
C ++源代码/功能: (C++ Source Code/Function:)
#include<bits/stdc++.h>
using namespace std;
int firstIndex(int input[], int size, int x, int currIndex){
if(size==currIndex){
return -1;
}
if(input[currIndex] == x){
return currIndex;
}
return firstIndex(input,size,x,currIndex+1);
}
int main(){
int input[] = {9,8,10,8};
int x = 8;
int size = 4;
cout<<firstIndex(input,size,x,0);
return 0;
}
Output
输出量
1
c ++递归算法数的计数