K 最近使用 (MRU) 应用程序的程序
给定一个整数K和一个包含N个整数的数组arr[] ,其中包含系统中打开的应用程序的ID ,其中
- arr[0]是当前正在使用的应用程序
- arr[1]是最近使用的应用程序,并且
- arr[N – 1]是最近最少使用的应用程序。
任务是当使用系统的用户按Alt + Tab正好K次时打印数组的内容。请注意,按Alt + Tab键后,应用程序打开指针将从第 0 个索引向右移动,具体取决于按下的次数,因此按下结束的应用程序将移动到第 0 个索引,因为这将成为最近的打开的应用程序。
例子:
Input: arr[] = {3, 5, 2, 4, 1}, K = 3
Output: 4 3 5 2 1
User want to switch to the app with id 4, it’ll become the currently active app and the previously active app (with id 3) will be the most recently used app.
Input: arr[] = {5, 7, 2, 3, 4, 1, 6}, K = 10
Output: 3 5 7 2 4 1 6
方法:获取用户想要切换到的应用程序的索引,即appIndex = K % N 。现在,当前活动的应用程序将是arr[appIndex]并且索引范围[0, appIndex – 1]中的所有其他应用程序必须向右移动 1 个元素。
下面是上述方法的实现:
C++14
// C++ implementation of the approach
#include
using namespace std;
// Function to update the array
// in most recently used fashion
void mostRecentlyUsedApps(int* arr, int N, int K)
{
int app_index = 0;
// Finding the end index after K presses
app_index = (K % N);
// Shifting elements by 1 towards the found index
// on which the K press ends
int x = app_index, app_id = arr[app_index];
while (x > 0) {
arr[x] = arr[--x];
}
// Update the current active app
arr[0] = app_id;
}
// Utility function to print
// the contents of the array
void printArray(int* arr, int N)
{
for (int i = 0; i < N; i++)
cout << arr[i] << " ";
}
// Driver code
int main()
{
int K = 3;
int arr[] = { 3, 5, 2, 4, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
mostRecentlyUsedApps(arr, N, K);
printArray(arr, N);
return 0;
}
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to update the array
// in most recently used fashion
static void mostRecentlyUsedApps(int []arr, int N, int K)
{
int app_index = 0;
// Finding the end index after K presses
app_index = (K % N);
// Shifting elements by 1 towards the found index
// on which the K press ends
int x = app_index, app_id = arr[app_index];
while (x > 0)
{
arr[x] = arr[--x];
}
// Update the current active app
arr[0] = app_id;
}
// Utility function to print
// the contents of the array
static void printArray(int []arr, int N)
{
for (int i = 0; i < N; i++)
Console.Write(arr[i]+" ");
}
// Driver code
static void Main()
{
int K = 3;
int []arr = { 3, 5, 2, 4, 1 };
int N = arr.Length;
mostRecentlyUsedApps(arr, N, K);
printArray(arr, N);
}
}
// This code is contributed by mits
Javascript
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int[] num = { 3, 5, 2, 4, 1 };
int size = num.length;
// 8,6,7,9,0,2,1,12,89
int d = 3;
int appIndex = d % size;
int appId = num[appIndex];
for (int i = appIndex; i > 0; i--) {
num[i] = num[i - 1];
}
num[0] = appId;
for (int i = 0; i < num.length; i++) {
System.out.print(" " + num[i]);
}
}
}
输出
4 3 5 2 1
时间复杂度: O(N)