日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2023/12/1 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c ++递归算法数的计数_C ++程序使用数组中的递归查找数字的最后一次出现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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:49 8 10 88Output: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 ++遞歸算法數的計數

總結

以上是生活随笔為你收集整理的c ++递归算法数的计数_C ++程序使用数组中的递归查找数字的最后一次出现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。