주어진 숫자 k와 배열 arr[n]은 시스템에서 열린 앱의 ID를 저장하는 n개의 정수 요소를 포함합니다. 작업은 k 개의 가장 최근에 사용한 앱을 표시하는 것입니다. 예를 들어 alt+tab을 누르면 모든 최근 앱이 표시되고 가장 최근의 앱은 가장 최근의 것보다 먼저 표시됩니다. 모든 id의 위치는 시스템의 다른 앱을 나타냅니다 -
다음과 같습니다 -
- Id in arr[0]은 현재 사용 중인 앱의 ID입니다.
- id in arr[1]은 가장 최근에 사용한 앱의 ID입니다.
- Id in arr[n-1]은 가장 최근에 사용된 앱의 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 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