C++ 實現最近使用 (MRU) 應用程式


給定一個數字 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 設為當前 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 print array elements
   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;
// Function to update the array in most recently used fashion
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;
}
//print array elements
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

更新於: 2019-12-23

1K+ 閱讀量

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.