给定一个数字k和一个数组arr [n],其中包含n个整数元素,这些整数元素存储系统中打开的应用程序的ID。任务是显示k个最近使用的应用程序,例如当我们按alt + tab键时,显示所有最近使用的应用程序,而最近显示的则是最近显示的应用程序。每个id的位置代表系统中不同的应用程序-
它们如下-
arr [0]中的ID是当前正在使用的应用的ID。
arr [1]中的ID是最近使用过的应用的ID。
arr [n-1]中的id是最近最少使用的应用程序的id。
注意-当我们按Alt + Tab键时,会有一个指针从当前索引0开始在所有打开的应用程序中移动。
Input: arr[] = {1, 2, 3, 4, 5}, k=2
Output: 3 1 2 4 5
Explanation: We wished to switched the app with id 3, so it will become the currently
active app and other active apps will be the most recently used now
Input: arr[] = {6, 1, 9, 5, 3}, k=3
Output: 5 6 1 9 3我们将用来解决上述问题的方法-
以数组arr [n]和k作为输入。
获取索引,即用户要切换的应用的k。
使索引k上的id为当前,然后按顺序排列。
打印结果。
Start
Step 1-> declare the function to find k most recently used apps
void recently(int* arr, int size, int elem)
Declare int index = 0
Set index = (elem % size)
Declare and set int temp = index, id = arr[index]
Loop While temp > 0
Set arr[temp] = arr[--temp]
End
Set arr[0] = id
Step 2-> declare function to 打印数组元素
void print(int* arr, int size)
Loop For i = 0 and i < size and i++
Print arr[i]
End
Step 3-> In main() Declare and set for elements as int elem = 3
Declare array as int arr[] = { 6, 1, 9, 5, 3 }
Calculate size as int size = sizeof(arr) / sizeof(arr[0])
Call recently(arr, size, elem)
Call print(arr, size)
Stop#include <bits/stdc++.h>
using namespace std;
//以最近使用的方式更新数组的功能
void recently(int* arr, int size, int elem) {
int index = 0;
index = (elem % size);
int temp = index, id = arr[index];
while (temp > 0) {
arr[temp] = arr[--temp];
}
arr[0] = id;
}
//打印数组元素
void print(int* arr, int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
int main() {
int elem = 3;
int arr[] = { 6, 1, 9, 5, 3 };
int size = sizeof(arr) / sizeof(arr[0]);
recently(arr, size, elem);
cout<<"array in most recently used fashion : ";
print(arr, size);
return 0;
}输出结果
array in most recently used fashion : 5 6 1 9 3