c ++递归算法数的计数_C ++程序使用数组中的递归查找数字的最后一次出现

给定一个数组和整数x,该算法通过递归找到x在数组中的最后一个索引。如果x不存在,返回-1。从数组的0索引开始递归遍历。示例中,当x为8时,其在数组的最后一个出现位置是索引3。
摘要由CSDN通过智能技术生成

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 ++递归算法数的计数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值