数组是专门用于在一系列内存区域中保留同类型数据的数据结构。使用数组的主要好处是我们可以使用索引参数从任何位置访问它们。然而,插入和删除数据需要顺序操作,这将使得这个数据结构变成线性数据结构。我们可以简单地使用方括号中的索引或位置号来从数组中提取元素。本文将演示如何在C++中从数组中读取最近的k个数字。
理解概念并通过示例进行说明
Given array A = [10, 14, 65, 85, 96, 12, 35, 74, 69]
We have another number k = 4
The number of elements in A is 9
The output will be the last k elements from A, which are:
12, 35, 74, 69
登录后复制
We have the elements inside the array for every array, and the quantity n is also crucial. The number n indicates how many valid elements are there in an array. The size of the array might not match the n. Although an array can have a maximum of Z elements, only n of them must be valid; the remaining slots are empty. In this case, k must be less than or equal to n in order to retrieve the kth element from the array. Before taking up the components, we must inspect it. For a better understanding, let's have a look at the algorithm.
算法
-
读取一个数组 A 作为输入。同时接受元素的数量:n 和 k,以读取 A 中的前 k 个元素
-
创建一个空数组 B
-
如果 k < n,则
-
for i in range 0 to k - 1, do
-
B[ i ] = A[ n - k + i ]
-
-
end for
-
-
end if
-
返回 B
Example
#include
# define Z 50
using namespace std;
void displayArr(int arr[], int n){
for( int i = 0; i < n; i++ ){
cout